<button onclick="alert(‘Hello‘)">Say hello</button>
上面这行代码,将按钮点击后的弹窗操作在标签声明的时候就绑定了.
<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript">
        window.onload = function () {
            // Event binding using onXXX property from JavaScript
            var helloBtn = document.getElementById("helloBtn");
            helloBtn.onclick = function (event) {
                alert("Hello Button");
            }
        }
    </script>
</head>
<body>
<button id="helloBtn">Say hello</button>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript">
        window.onload = function () {
            // Event binding using addEventListener
            var helloBtn = document.getElementById("helloBtn");
            helloBtn.addEventListener("click", function (event) {
                alert("Hello.");
            }, false);
        }
    </script>
</head>
<body>
<button id="helloBtn">Say hello</button>
</body>
</html>
// Event binding using a convenience method
$("#helloBtn").click(function (event) {
    alert("Hello.");
});
// The many ways to bind events with jQuery
// Attach an event handler directly to the button using jQuery‘s
// shorthand `click` method.
$("#helloBtn").click(function (event) {
    alert("Hello.");
});
// Attach an event handler directly to the button using jQuery‘s
// `bind` method, passing it an event string of `click`
$("#helloBtn").bind("click", function (event) {
    alert("Hello.");
});
// As of jQuery 1.7, attach an event handler directly to the button
// using jQuery‘s `on` method.
$("#helloBtn").on("click", function (event) {
    alert("Hello.");
});
// As of jQuery 1.7, attach an event handler to the `body` element that
// is listening for clicks, and will respond whenever *any* button is
// clicked on the page.
$("body").on({
    click: function (event) {
        alert("Hello.");
    }
}, "button");
// An alternative to the previous example, using slightly different syntax.
$("body").on("click", "button", function (event) {
    alert("Hello.");
});
 
标签: JavaScript, Web, DOM, jQuery
[DOM Event Learning] Section 1 DOM Event 处理器绑定的几种方法
原文:http://www.cnblogs.com/liu-Gray/p/4809574.html