Toggle next element with jQuery

若如初见. 提交于 2019-12-01 21:29:52

Change your code so that you get the extra options div directly after the clicked link like this:

buttonSubmit.click(function (e) {
    e.preventDefault();
    // Get the extra options directly after the clicked link
    var extraOptions = $(this).closest('p.actions').next('div.extra-options-tickets');

    if(extraOptions.is(":visible")) {
        extraOptions.hide();
    } else {
        extraOptions.fadeIn(450);
    };

});

Description

You should use jQuery.parent() and jQuery.next() to get this done. Check out the sample and this jSFiddle Demonstration.

Sample

Html

<p class="actions">
    <a href="#" class="button" title="Toevoegen"><span>Toevoegen</span></a>
</p>
<div class="extra-options-tickets" style="display: none; ">
text
</div>

<p class="actions">
    <a href="#" class="button" title="Toevoegen"><span>Toevoegen</span></a>
</p>
<div class="extra-options-tickets" style="display: none; ">
text
</div>

jQuery

$(".button").click(function () {
    var div = $(this).parent().next();
    if(div.is(":visible")) {
        div.hide();
    } else {
        div.fadeIn(450);
    };
});

More Information

see this example I made for you: http://jsfiddle.net/manuel/PmNwh/

I use the jquery next() function to get the first .extra-options-tickets

The this element represents the element that invoked the action witch in your case, it's the <a> element.

and it seams you want to only show, the next <div class="extra-options-tickets"> and not all of them, so you need to think like this:

In this code, if what fires the click is the <a> (your selector), how do I go to reach the <div> I want to show?

<p class="actions">
    <a href="#" class="button" title="Toevoegen"><span>Toevoegen</span></a>
</p>
<div class="extra-options-tickets" style="display: none; ">text</div>

From <a> you can navigate to the previous element, witch is the <p class="actions"> and the next element (the <div>) is the one I want...

translating this to code:

var extraOptions = $(this) // my <a> element
                     .prev() // previous element (<p class="actions">)
                     .next(); // next element from <p> is <div class="extra-options-tickets">

you can always make more generic so you can safely add more elements in between, for example:

instead of calling the .prev() (previous element), find the closest elemnt with a class of actions and from there, find the next element down the DOM with a class of extra-options-tickets, translating:

var extraOptions = $(this).closest(".actions").next(".extra-options-tickets");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!