解绑内联onClick不能在jQuery中工作?

Pol*_*878 22 javascript jquery

好的,我想知道如何在jQuery中取消绑定内联onclick事件.你认为.unbind()会起作用,但事实并非如此.

要自己测试一下,请使用以下HTML和JavaScript:

function UnbindTest() {
    $("#unbindTest").unbind('click');
}

function BindTest() {
    $("#unbindTest").bind('click', function() { alert("bound!"); });
}


<button type="button" onclick="javascript:UnbindTest();">Unbind Test</button>
<button type="button" onclick="javascript:BindTest();">Bind Test</button>
<button type="button" onclick="javascript:alert('unbind me!');" id="unbindTest">Unbind Button</button>
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,取消绑定并不解除内联onclick事件的绑定...但它确实解除了添加的click事件的绑定bind().

所以,我想知道是否有办法解除内联onclick事件,而不是执行以下操作:

$("#unbindTest").get(0).onclick = "";
Run Code Online (Sandbox Code Playgroud)

谢谢

Mar*_*rth 34

jQuery的unbind不会对onclick属性起作用- 它只适用于通过bind并因此可用的函数$(...).data('events').您必须使用removeAttr删除onclick.

阅读此问题以获取更多信息.

  • snap ... $("#unbindTest").removeAttr('onclick'); 工作. (3认同)