<button onclick="alert('Hello')">Say hello</button>
上面这行代码,将按钮点击后的弹窗操作在标签声明的时候就绑定了.
这是一种糟糕的方法,原因如下: 1.View code(HTML)和交互code(JS)强耦合了.这意味着每次我们想改方法,都需要编辑HTML. 2.可扩展性差.如果这个方法需要被附加在多个元素上,重复的代码会让页面膨胀,并且维护困难.<!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>这种方法比较简单,并且会覆盖之前的handler,也没有什么浏览器兼容的问题.
<!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>这种方法在现代的浏览器上是工作良好的,但是在IE9之前的IE浏览器是没有这个方法的,它们用attachEvent().
// Event binding using a convenience method$("#helloBtn").click(function (event) { alert("Hello.");});jQuery监听事件有很多种方法:
// 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.");});jQuery 1.7开始,所有的事件绑定方法最后都是调用.on()方法. 上面这个例子中,前三个方法调用是等价的. 第四个和第五个方法,监听的是body上所有button元素的click事件. DOM树里更高层的一个元素监听发生在它的children元素上的事件,这个过程叫做事件代理(eventdelegation).
新闻热点
疑难解答