当我尝试使用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()
问题吗?
发布于 2011-01-18 07:43:31
查看HTML不应该是你的声明:
$(this).next(".info_section").toggle(400);
be:
$(this).parent().next(".info_section").toggle(400);
发布于 2012-08-01 00:54:35
虽然你已经有了有效的答案,但我想给你一个关于切换-
和+
的建议,我建议使用text()
而不是HTML,并使用固有的text
(对于text()
,对于html()
,使用html
):
$(".toggle_button").live('click', function() {
$(this).text(function(index,text) {
return text == '-' ? '+' : '-';
});
$(this).parent().next(".info_section").toggle(400);
});
此外,我建议缓存您的$(this)
,如果您不止一次调用它,那么使用缓存是值得的,以避免随后必须重新创建它,从而导致:
$(".toggle_button").live('click', function() {
var $this = $(this);
$this.text(function(index,text) {
return text == '-' ? '+' : '-';
});
$this.parent().next(".info_section").toggle(400);
});
当然,如果您使用的jQuery版本高于或包括1.7,那么您应该使用on()
方法,而不是(从jQuery 1.7开始)不推荐使用的live()
,这将提供:
$(".toggle_button").on('click', function() {
var $this = $(this);
$this.text(function(index,text) {
return text == '-' ? '+' : '-';
});
$this.parent().next(".info_section").toggle(400);
});
然而,这实际上只是一个建议,不幸的是,它是作为一个答案发布的,以防止无法理解的代码被粘贴到注释中。
参考文献:
html()
.live()
.on()
.text()
.https://stackoverflow.com/questions/4717903
复制相似问题