【问题标题】:jQuery toggle more button toggle multiple divsjQuery切换更多按钮切换多个div
【发布时间】:2018-12-10 10:49:03
【问题描述】:

我已经为切换按钮编写了 jquery...

$(document).ready(function(){
    /* Needs to be re-written for multiple questions */
    $(".full_question").hide();
    $('.question a').after('<a class="show_full_question" href="#">more</a>');

    $('.show_full_question').click(function() {
    var el = this;
        $(".full_question").toggle(function() {
            $(el).text($(el).text() == 'less' ? 'more' : 'less');
            $(el).toggleClass("hide_full_question");
        });
    });
});

它在完整的问题宽度和部分宽度之间切换。但是当点击它时,它会切换页面上的所有问题。我怎样才能让它只切换一个?

我知道它与 $(this) 有关,但不确定它的去向...我不介意在必要时更改 html。

html 是...

<h3 class="question">
  <a href="#">What size is the circumference of the earth? I don't really know what it is! Help me! What size is the...
    <span class="full_question"> circumference of the earth? I really don't know!</span>
  </a>
</h3>

【问题讨论】:

  • 能否也添加html代码(或sn-p)
  • 是的,发布问题的 html

标签: javascript jquery toggle


【解决方案1】:

问题是$(".full_question").toggle(),将使用full_question 类切换所有元素。您需要以某种方式将当前被点击的元素与正确的 full_question 联系起来。

由于您在同一个父级下有一个full_question 和一个show_full_question 按钮,您可以使用jQuery 获取父级并找到要切换的问题:

$(this).parent().find(".full_question").toggle()

如果您确定 HTML 结构不会改变,您也可以这样做:

$(this.previousSibling.childNodes[1]).toggle()

这是jsfiddle example

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-15
    • 1970-01-01
    相关资源
    最近更新 更多