【问题标题】:jQuery next() not working with live()jQuery next() 不能与 live() 一起使用
【发布时间】:2011-01-17 21:08:41
【问题描述】:

当我尝试使用 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() 问题?

【问题讨论】:

  • 您需要显示我认为适用的 HTML。 .toggle_button 元素之后是否可能没有 .info_section?或者您是在使用上面一行中的.html() 调用来破坏this?尝试改用.text()
  • 到底是什么问题? 你的 HTML 是什么样子的?next() 只会返回一个元素当且仅当this 的下一个兄弟元素具有类info_section。它确实返回类info_section的下一个兄弟。
  • @Orbling: html 只影响内容,不影响元素本身。
  • 发布您的实际代码,我不知道您的问题是什么。我可以让它正常工作:jsfiddle.net/jWR6A 但我所做的只是随机猜测你想做什么。发布 HTML。或者更好地描述 .next 没有做什么,因为它完全按照文档所说的去做。
  • @Felix Kling:好点子,但考虑到正在进行的更改,使用.text() 仍然会更好。

标签: jquery live next


【解决方案1】:

看HTML不应该是你的说法:

$(this).next(".info_section").toggle(400);

是:

$(this).parent().next(".info_section").toggle(400);

【讨论】:

    【解决方案2】:

    虽然您有有效的答案,但我想留下一个关于您切换 -+ 的建议,我建议使用 text() 而不是 HTML,并使用固有的 text(对于text(), htmlhtml()):

    $(".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);
    });
    

    不过,这实际上只是建议,不幸的是,作为答案发布,以防止将难以理解的代码粘贴到评论中。

    参考资料:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-14
      • 2015-09-04
      • 2021-05-09
      • 2020-01-28
      相关资源
      最近更新 更多