jquery:替换 onclick 事件

jquery: Replace onclick event

本文关键字:事件 onclick 替换 jquery      更新时间:2023-09-26

我有以下代码:

  $('#tableA').find("#expand_" + row_id).prop("onclick", null);
  $('#tableA').find("#expand_" + row_id).prop("onclick", 'expandAndShow('+row_id+')');
  $('#tableA').find("#expand_" + row_id).removeClass('icon-plus-sign');
  $('#tableA').find("#expand_" + row_id).addClass('icon-ok-sign');

我想用新方法替换以前链接onlick方法。它不起作用。但是,removeClassaddClass运作良好。我错过了什么吗?

使用 jQuery 删除内联属性:

$('#tableA').find('#expand_' + row_id).removeAttr('onclick');

对于IE <9,您应该使用:

.prop('onclick', null);

如文档中所述。
但是,我确实想知道为什么您将find与ID选择器一起使用。我相信我说find返回一个 jQ 对象数组是对的。没有一个 DOM 对象。
也许:

$('#expand_' + row_id).prop('onclick', null);

更合适。顺便说一下,要将 onclick 属性替换为另一个属性,您不需要 2 次prop调用:

$('#expand_' + row_id).prop('onclick', 'expandAndShow('+row_id+')');

基本上通过设置另一个处理程序来删除原始onclick处理程序。总而言之,这种事情最好使用委派来完成:

$('#tableA').on('click', '*[id^=expand_]', function()
{
    alert($(this).attr('id').replace('expand_',''));
});

此代码处理 #tableA 元素的所有子元素上具有 id 的所有单击事件,这些事件以 expand_ 开头。然后,我继续提醒该 id,而不使用 expand_ 子字符串。

这应该有效

$('#tableA').find("#expand_" + row_id).unbind('click');
$('#tableA').find("#expand_" + row_id).on('click',expandAndShow(row_id));