开发者

jQuery toggle more button toggle multiple divs

开发者 https://www.devze.com 2023-02-25 18:50 出处:网络
I\'ve written jquery for a toggle button... $(document).ready(function(){ /* Needs to be re-written for multiple questions */

I've written jquery for a toggle button...

$(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).toggleCla开发者_Go百科ss("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.

The html is...

<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. You need to somehow link the current element being clicked with the proper 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:

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

If you are certain that HTML structure won't change you can also do:

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

Here's a jsfiddle example.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号