javascript - jQuery 点击一个动态添加的元素

标签 javascript jquery html onclick

我使用 jQuery 创建了一个 HTML 表格,我想点击第二行中的第一个链接。 生成的 HTML 看起来像这样

<tr><td>4</td><td>text</td></tr>
<tr id="xrow22" class="xrow"><td colspan="2"><a>0</a><a>1</a></td></tr>

当我使用鼠标单击该行时,处理点击的函数运行良好

$('table').on('click', '[id^=xrow] a', function(){ ...

当我尝试从另一个调用此函数时,它不起作用。我使用警报来查看一些值,令人惊讶的是下面的代码警报(第二个值应该是 0)

<a>0</a><a>1</a>,,[object Object]

代码:

$('table').on('click', 'tr:not(.xrow)', function(e){
  $(this).next().children('td:first-child a:first-child').click();
  alert($(this).next().children('td:first-child').html() +','+ $(this).next().children('td:first-child a:first-child').text() +','+ $(this).next().children('td:first-child a:first-child'));
});

最佳答案

您可以使用 $().live() 函数代替 $().on() 函数。基本上,当您创建一个新元素时,jquery 不会重新运行,甚至不会将点击附加到它。 http://api.jquery.com/live/

关于javascript - jQuery 点击一个动态添加的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39183585/

相关文章:

javascript - 元素在变换比例之前跳跃

javascript - 由于 Javascript 悬停效果,链接在移动设备上不起作用

javascript - 使用Javascript隐藏html中的元素或特定id

html - 辅助悬停过渡不起作用

javascript - 将 Canvas 划分为独立的空间

javascript - 数组中的 base64 图像文件在 javascript 中未定义

javascript - Image Slider JS 的一些问题

html - Ruby on Rails 模型,日历栏作为列,不同模型的主键作为行?

javascript - 服务器进程完成后清除ajax响应

javascript - 如何在没有事件的情况下移动 div 的子级