jQuery移除在视图中指定的事件处理程序

jQuery remove event handler which is specified in the View

本文关键字:事件处理 程序 视图 jQuery      更新时间:2024-03-08

我的理解是,当使用unbindoffjQuery方法时,我应该能够从元素中删除事件处理程序,如下所示

在视图中创建的文本框,其中应用了onkeypress事件处理程序

@Html.TextBoxFor(Function(m) m.sometext, New With {.onkeypress = "eventhandler();", .id = "theID"}

试图删除事件的JavaScript

function eventhandler()
{
    alert("should only hit once");
    // this doesnt unbind the event
    $("#theID").unbind("onkeypress");
    // Nor does
    $("#theID").off();
    //???
}

我的想法可能是unbind只适用于bind,而off只适用于使用on的情况。我这么说是因为jQuery API网站声明

.of()方法删除附加了.on()的事件处理程序

如果是这种情况,我可以完全不在视图中应用处理程序吗?

我想补充一点,我想在视图中执行此操作,并且我想应用来自ViewModel 的唯一ID

任何帮助都会对有所帮助

感谢

您可以使用removeAttr()

$('#theID').removeAttr('onkeypress'); 

将事件处理程序设置为null

$('#theID'')[0].onkeypress = null;