我有以下代码:
$('#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
方法。它不工作。但是,removeClass
和 addClass
运行良好。我错过了什么吗?
最佳答案
使用 jQuery 删除内联属性:
$('#tableA').find('#expand_' + row_id).removeAttr('onclick');
就是这样,但是,对于 IE < 9,您应该使用:
.prop('onclick', null);
作为explained in the docs .
但是,我确实想知道您为什么要将 find
与 ID 选择器一起使用。我相信我说 find
返回 jQ 对象的 array 是对的。不是单个 DOM 对象。
也许:
$('#expand_' + row_id).prop('onclick', null);
更合适。要用另一个属性替换 onclick
属性,您不需要调用 2 个 prop
,顺便说一句:
$('#expand_' + row_id).prop('onclick', 'expandAndShow('+row_id+')');
基本上删除原来的onclick
处理程序,通过设置另一个处理程序。总而言之,这种事情最好使用委托(delegate)来完成:
$('#tableA').on('click', '*[id^=expand_]', function()
{
alert($(this).attr('id').replace('expand_',''));
});
此代码处理 #tableA
元素的所有子元素上的所有点击事件,这些元素的 ID 以 expand_
开头。然后我继续提醒那个 id,没有 expand_
子字符串。
关于javascript - jquery: 替换 onclick 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20046170/