js(jquery)绑定点击事件

<button type="submit" id="test">test</button>

第一种

$("#test").click(function(event){
/* Act on the event */});

另外一种

document.getElementById('#foo').addEventListener('click', function() {
/* Act on the event */}, false);

第三种

html

     <button type="submit" id="test" onclick="test()">test</button>

js

     function test(){/* Act on the event */}

第四种

$('#test').bind('click', function() {/* Act on the event */ });


第五种

$( "#test" ).on( "click", function() {/* Act on the event*/ } );

第一种和另外一种的效果是一样,能够附加多个事件处理函数,并非仅仅有使用jquery才干做到。 第三种方法不推荐使用。原则上HTML代码仅仅能体现网页的结构,详细的行为应该使用javascript代码进行绑定。

除非页面上绑定事件的元素超过上万个,否则响应速度的时候就不必纠结了,仅仅做个事件绑定还是非常快的。我測试了一下,使用addEventListener绑定3000次,耗时3-4毫秒。

假设项目中统一使用jQuery的话,建议使用第一种做法。顺便还攻克了IE的不兼容问题。



原文地址:https://www.cnblogs.com/mfmdaoyou/p/6784415.html