delegate() TBODY TR 中的一个类
我正在尝试使用 .live()
和 .delegate()
来获取在加载 JS 后添加到 DOM 的元素。
这是可行的:
$(".mouseRow tbody tr").live("click", function(event) { });
但这不起作用,也没有给出任何错误,这让我认为这是一个 DOM 计时问题:
$(".mouseRow").delegate("tbody tr", "click", function(event) { });
我是否错误地调用了 .delegate()
函数,也许使用了“tbody tr
”声明?或者这是 DOM 计时的问题,因为元素尚不存在(这就是我首先使用 live()
的原因)?
I'm experimenting with .live()
and .delegate()
for elements that are added to DOM well after my JS is loaded.
This works:
$(".mouseRow tbody tr").live("click", function(event) { });
But this does not work and no errors are given, which makes me think it is a DOM timing thing:
$(".mouseRow").delegate("tbody tr", "click", function(event) { });
Am I calling the .delegate()
function incorrectly, perhaps with the "tbody tr
" statement? Or is this a problem with the DOM timing since the elements do not exist yet (which is why I used live()
in the first place)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您在注释中说过.mouseRow
是您要应用于tr
元素的类,您需要:mouseRow
是table
元素上的一个类,您希望在其中挂钩tr
元素上的点击。如果table.mouseRow
元素在您挂接处理程序时就存在,您可能需要这样:挂接
tbody
上的click
事件table.mouseRow
中的 code>,当它发生时,检查从实际单击的元素到tbody
的元素链,以查看其中是否有任何与选择器tr
。如果是这样,它会使用this
引用相关行来调用事件处理程序。或者从 jQuery 1.7 开始,建议使用
on
来处理此类事情:(请注意,参数的顺序略有不同。)
无论哪种方式,当
table .mouseRow tbody
已在 DOM 中。如果还没有,您需要进一步深入 DOM,也许一直到document
:IfYou've said in the comments that.mouseRow
is a class you're applying totr
elements, you want:mouseRow
is a class on thetable
element within which you want to hook clicks ontr
elements. If thetable.mouseRow
elements will exist as of when you're hooking up your handlers, you probably want this:That hooks the
click
event ontbody
within thetable.mouseRow
, and when it occurs checks the chain of elements from the one actually clicked up totbody
to see if any of them match the selectortr
. If so, it calls the event handler withthis
referencing the row in question.Or as of jQuery 1.7, the recommendation is to use
on
for this sort of thing:(Note that the order of arguments is slightly different.)
Either way, you execute that statement when the
table.mouseRow tbody
is already in the DOM. If it won't be there yet, you need to go further up the DOM, perhaps all the way todocument
: