简体   繁体   English

jQuery单击动态添加的元素

[英]jQuery click on a dynamically added element

I created a HTML table using jQuery and I'd like to perform a click on the first link inside the 2nd row. 我使用jQuery创建了一个HTML表,我想单击第二行内的第一个链接。 The generated HTML looks like this 生成的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>

The function handling clicks works well when I click the row using my mouse 当我使用鼠标单击行时,处理点击的功能效果很好

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

When I try to call this function from another one, it doesn't work. 当我尝试从另一个函数调用此函数时,它不起作用。 I used alert to see some values and surprisingly the below code alerts (2nd value should be 0) 我使用alert来查看一些值,并且令人惊讶的是下面的代码警报(第二个值应为0)

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

Code: 码:

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

Instead of the $().on() function you can use the $().live() function. 可以使用$()。live()函数代替$()。on()函数。 Basically when you create a new element, jquery doesn't rerun and attach the click even to it. 基本上,当您创建新元素时,jquery不会重新运行,甚至不会向其附加点击。 http://api.jquery.com/live/ http://api.jquery.com/live/

When I use $(this).next().children('td:first-child').children('a:first-child').text(); 当我使用$(this).next().children('td:first-child').children('a:first-child').text(); I get the expected result. 我得到了预期的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM