简体   繁体   English

jQuery中的单击事件监听器

[英]On click event listener in jquery

I had write a simple code to delete a record on a table, 我编写了一个简单的代码来删除表上的记录,

<td><a href = "#" class = "delete">Delete</a></td>

$('.delete').on('click', function() { 
     console.log('try');
});

The problem is that, If how many td's on the document I mean if there are 10 td's with delete class, it logs the try strign 10 times also. 问题是,如果我的意思是文档中有多少td,如果有10个td's具有delete类,它也会记录try strign 10次。

Am I using on click event listener wrong or this is an issue on the jquery. on click事件监听器on click使用的是错误的还是这是jquery上的问题。 Thank you. 谢谢。

A single call to .on() will only ever result in a single event handler being launched. 单个调用.on()只会导致启动单个事件处理程序。

IMHO, the most likely explanation for your fault is that you are actually calling .on() multiple times - perhaps inside the loop that's creating the <td> elements? 恕我直言,对您的错误的最可能的解释是您实际上多次调用.on() -也许在创建<td>元素的循环内?

Within the single handler you can use DOM traversal to identify which column or element was clicked, and act accordingly. 在单个处理程序中,您可以使用DOM遍历来确定单击了哪个列或元素,并采取相应的措施。 If, for example, you wanted to delete the current row you could use this: 例如,如果您想删除当前行,则可以使用以下命令:

for (...) {
    // populate the table here
}

// handler will remove the row containing the clicked ".delete" link
$('.delete').on('click', function() {
    $(this).closest('tr').remove();
});

EDIT based on new information from the OP, the problem is actually duplicate re-registration of the same handler over and over, each time a row is added. 根据来自OP的新信息进行编辑 ,实际上,问题是每次添加一行时,一次又一次地重复同一处理程序的重复注册。

In this case, the best solution is event delegation , where you put the handler on the table (just once), rather than on the individual elements: 在这种情况下,最好的解决方案是事件委托 ,您可以将处理程序放在表上 (仅一次),而不是放在单个元素上:

$('#mytable').on('click', '.delete', function() {
    // do your delete stuff here
});

Note the additional .delete parameter to .on - this tells jQuery which particular elements within the table you're interested in - the clicked element will be passed as this . 请注意额外.delete参数.on -这告诉jQuery的你感兴趣的表中的特定元素-点击的元素会被传递this

You can make this call before the table is even populated, and it'll work on any .delete element found inside the table, even ones added later, dynamically. 您可以在填充表之前进行此调用,它可以在表中找到的任何.delete元素(甚至以后添加的动态元素)上动态运行。

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

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