javascript - jquery: 替换 onclick 事件

标签 javascript jquery jquery-ui

我有以下代码:

  $('#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);

作为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/

相关文章:

javascript - 带搜索的分页

javascript - jquery ui tabs盲效应不起作用

jquery - 动态设置 jQuery UI 工具提示的位置

javascript - 多个文件拖放区域

Javascript 绝对定位

php - PHP 搜索建议中的排序结果

javascript - Bootstrap 模态 : Undefined

javascript - jQuery自动完成 'focus'事件触发,但没有反向等效项。我徘徊离开,但变化依然存在

javascript - 如何使用 mottie 键盘输入美分并将它们保留在那里?

javascript - React 中 useLatest 的并发安全版本?