[英]jquery click() doesn't work
I have a problem with jQuery click() function. 我对jQuery click()函数有问题。
I use this function to programatically click on a link which calls an ajax function that adds a new object to the database. 我使用此函数以编程方式单击一个链接,该链接调用一个ajax函数,该函数将一个新对象添加到数据库中。
When I submit my form, a tr is added in the object datatable for my new object with new link and I want to programatically click on this new link to load object properties and display them. 当我提交表单时,在带有新链接的新对象的对象数据表中添加了tr,我想以编程方式单击此新链接以加载并显示对象属性。
The problem is that the new tr with td and link doesn't exist in DOM and the function $.('#elem').click')
doesn't work. 问题是DOM中不存在带有td和link的新tr,并且功能$.('#elem').click')
不起作用。
I saw in others post that I have to bind click event with the new .on function like this : 我在其他帖子中看到,我必须将click事件与新的.on函数绑定在一起,如下所示:
$('#parent-items').on('click', 'elem', function() {
// [...]
});
I don't know what I have to write in place of [...], at the end of my javascript code, I call the click function like this : 我不知道要写些什么来代替[...],在我的JavaScript代码末尾,我这样调用click函数:
$('#myelem').click();
Thanks for your help 谢谢你的帮助
Not that hard, actually. 实际上并不难。 :) :)
<table id="list">
<tr>
<td>John</td>
<td><a class="btn-hi">Say Hi!</a></td>
<td><a class="btn-bye">Say Goodbye!</a></td>
</tr>
<tr>
<td>Lucy</td>
<td><a class="btn-hi">Say Hi!</a></td>
<td><a class="btn-bye">Say Goodbye!</a></td>
</tr>
<tr>
<td>Sam</td>
<td><a class="btn-hi">Say Hi!</a></td>
<td><a class="btn-bye">Say Goodbye!</a></td>
</tr>
</table>
<script>
$('#list').on('click', 'a', function() {
// Wrap the clicked <a> element with jQuery
var $this = $(this);
// Get the parent <tr> element
var $tr = $this.closest('tr');
// Get all (direct) children elements (<td>) that are inside the current <tr> element
var $tds = $tr.children();
// Get the text from the first <td> element in the current row
var name = $tds.eq(0).text();
// Get the type (class name) of clicked link
var type = $this.attr('class');
if (type == 'btn-hi') {
alert( 'Hi, ' + name + '!' );
} else if (type == 'btn-bye') {
alert( 'Goodbye, ' + name + '!' );
}
});
</script>
Have a look at this demo in JSBin: http://jsbin.com/welcome/38776/edit 在JSBin中查看此演示: http : //jsbin.com/welcome/38776/edit
The click event will get executed every time when user clicks on any <a>
element that is inside <table id="list">
element. 每当用户单击<table id="list">
元素内的任何<a>
元素时,click事件都将执行。 It's called "event delegation" - http://api.jquery.com/delegate/ 称为“事件委托” -http://api.jquery.com/delegate/
So, you can dynamically add more rows to the table and everything will still work. 因此,您可以向表中动态添加更多行,并且一切仍将正常进行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.