当我尝试使用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()
问题吗?
答案 0 :(得分:3)
查看HTML不应该是你的陈述:
$(this).next(".info_section").toggle(400);
是:
$(this).parent().next(".info_section").toggle(400);
答案 1 :(得分:1)
虽然您有正确的答案,但我想留下关于您切换-
和+
的建议,我建议您使用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);
});
这实际上只是建议,不幸的是,这是一个答案,以防止将难以理解的代码粘贴到评论中。
参考文献: