简体   繁体   English

jQuery切换更多按钮切换多个div

[英]jQuery toggle more button toggle multiple divs

I've written jquery for a toggle button... 我为切换按钮编写了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");
        });
    });
});

it toggles between the full question width and partial width. 它在完整的问题宽度和部分宽度之间切换。 But when clicked it toggles for all questions on the page. 但是当点击它时,它会切换页面上的所有问题。 How would I get it toggle only one? 我怎么才能让它只切换一个呢?

I know it has something to do with $(this) but not sure where it goes... I don't mind changing the html if necessary. 我知道它与$(this)有关,但不确定它在哪里......我不介意在必要时更改html。

The html is... 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>

The problem is $(".full_question").toggle() , will toggle all elements with the full_question class. 问题是$(".full_question").toggle() ,将使用full_question类切换所有元素。 You need to somehow link the current element being clicked with the proper full_question. 您需要以某种方式将当前单击的元素与正确的full_question链接起来。

Since you have one full_question and one show_full_question button under the same parent you can use jQuery to get the parent and find the question to toggle: 由于在同一父项下有一个full_question和一个show_full_question按钮,因此您可以使用jQuery获取父项并找到要切换的问题:

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

If you are certain that HTML structure won't change you can also do: 如果您确定HTML结构不会改变,您还可以:

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

Here's a jsfiddle example . 这是一个jsfiddle例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM