简体   繁体   English

jQuery .on()不绑定事件处理程序

[英]jQuery .on() not binding event-handler

I'm trying to attach an event handler to every row in a dynamically-changing table with no success (using jQuery version 1.11.0) * Edit: As many have pointed out, ' hover ' is depricated, but my problem also exists with other handlers* 我正在尝试将事件处理程序附加到动态更改表中的每一行但没有成功(使用jQuery版本1.11.0)*编辑:正如许多人所指出的那样,' hover '已被删除,但我的问题也存在于其他处理人员*

$('#tableBody tbody').on('hover', 'tr', function() {
    alert('hovering on a row');
});

The above code is pretty much identical to the jQuery documentation- http://api.jquery.com/on/ , and I've tried other variations, like 上面的代码与jQuery文档 - http://api.jquery.com/on/完全相同,我尝试过其他变体,比如

$(document).on('hover', '.tableRow', function(){...});

The event handler just isn't getting added. 事件处理程序就是没有添加。 I should note that the table's contents are retrieved though AJAX and then displayed, which is why I'm using the .on() method. 我应该注意,表的内容是通过AJAX检索然后显示的,这就是我使用.on()方法的原因。

Passing 'hover' as a string to .on() is no longer supported (removed in v1.9 as mentioned under the "Additional Notes" in the .on() documentation ). 不再支持将'hover'作为字符串传递给.on() (在.on()文档中的“Additional Notes”中提到的v1.9中删除)。 The equivalent is to use 'mouseenter mouseleave' instead, or if you just want to do something when the mouse enters the element(s) in question try: 相当于使用'mouseenter mouseleave' ,或者如果你只想在鼠标进入相关元素时做某事,请尝试:

$('#tableBody tbody').on('mouseenter', 'tr', function() {

Note that the #tableBody element would need to exist at the time that that runs, so you'd need to include that either in a document ready handler or in a script element at the end of the body. 请注意, #tableBody元素在运行时需要存在,因此您需要将其包含在文档就绪处理程序或正文末尾的脚本元素中。

And the id 'tableBody' sounds like it is assigned to the <tbody> element, which doesn't make sense when your selector also includes tbody as a child of #tableBody . 并且'tableBody'听起来像是分配给<tbody>元素,当你的选择器还包含tbody作为#tableBody的子元素时,这是没有意义的。

'mouseenter' event should work just fine. 'mouseenter'事件应该可以正常工作。

$('#myTable tbody').on('mouseenter', 'tr', function() {
    alert('hovering on a row');
});

This is the jsfiddle 这是jsfiddle

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

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