jQuery 事件处理程序堆叠

jquery event handlers stacking

本文关键字:程序 事件处理 jQuery      更新时间:2023-09-26

>我有这样的东西:http://jsfiddle.net/PTcw8/4/

<div id="container">
    <a href="#" onclick="javascript:alert('inline'); return false;"> show me </a>
    <br />
    <input type="button" value="click to change the links onclick event" onclick="javascript:changeOnClick(); return false;" />
</div>​
function changeOnClick() {
    $("#container a").unbind('click');
    $("#container a").on('click', function() {
        alert("changed on the fly");
    })
}​

该链接有一个内联的 onClick 事件,我无法取消绑定它并绑定新的处理程序,它们只是出于某种原因堆叠。

是否可以取消绑定内联处理程序?

如果以前使用.bind()附加了事件处理程序,则只能.unbind()事件处理程序:

使用 .bind(( 附加的事件处理程序可以使用 .unbind(( 删除。

对于内联事件处理程序,请使用:

$("#container a").removeAttr("onclick");

$("#container a")[0].onclick = null;

演示

我会这样做:

$(document).ready(
    function(){
       $("#container a").removeAttr("onclick");
       $("#container a").on('click', function() {
          alert("changed on the fly");
       })
    }
);