jQuery next() 无法与 live() 一起使用
当我尝试使用 jQuery next()
方法时,它无法与 live()
一起使用。
首先,这是我的代码:
$(".toggle_button").live('click', function() {
$(this).html($(this).html() == '-' ? '+' : '-');
$(this).next(".info_section").toggle(400);
});
这是 HTML
<div class='section_toggle_container'>
<div class='toggle_button'>-</div>
<strong>Driver Information:</strong>
</div>
<div class='info_section'>
info here
</div>
问题是否可能在于 .toggle_button
嵌套,导致 .info_section
无法访问?
第二行效果很好,因为它正在修改给定 live()
事件的元素。然而,第三行是问题所在。这是因为它使用了 next()
。
谁能帮我解决 next()
问题?
When I try and use the jQuery next()
method it doesn't work with live()
.
First off, here is my code:
$(".toggle_button").live('click', function() {
$(this).html($(this).html() == '-' ? '+' : '-');
$(this).next(".info_section").toggle(400);
});
Here's the HTML
<div class='section_toggle_container'>
<div class='toggle_button'>-</div>
<strong>Driver Information:</strong>
</div>
<div class='info_section'>
info here
</div>
Would the problem maybe lie in the fact that .toggle_button
is nested, making .info_section
unreachable?
The second line works great, because it's modifying the element given the live()
event. The third line, however, is where the problem's at. This is because it's using next()
.
Can anyone help me with a solution for my next()
problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
查看 HTML,您的声明不应该
是:
Looking at the HTML should't your statement:
be:
虽然您有可行的答案,但我想留下关于切换
-
和+
的建议,我建议使用text()
而不是 HTML,并使用固有的text
(对于text()
,html
对于html()
) :此外,我建议缓存您的
$(this)
,如果您多次调用它,那么值得使用缓存来防止随后重新创建它,从而导致:当然,如果您使用的 jQuery 版本大于或包含 1.7,那么您应该使用
on()
方法,而不是(自 jQuery 1.7 起)已弃用的live()
,这将给出:不过,这实际上只是建议,不幸的是,作为答案发布,以防止将难以理解的代码粘贴到评论中。
参考文献:
html()
。live()
。on()
。text()
。While you have the working answer, I wanted to leave a suggestion about your toggling of the
-
and+
, I'd suggest usingtext()
instead of HTML, and using the inherenttext
(fortext()
,html
forhtml()
):And, further, I'd suggest caching your
$(this)
, if you're calling it more than once it's worthwhile using caching to prevent having to recreate it subsequently, leading to:Of course, if you're using a version of jQuery greater than, or including, 1.7, then you should be using the
on()
method, rather than the (since jQuery 1.7) deprecatedlive()
, which would give:This really is just advice, though, unfortunately posted as an answer to prevent incomprehensible code being pasted into a comment.
References:
html()
.live()
.on()
.text()
.