简体   繁体   中英

Toggle div on Link[same link class on various] click Jquery

I have an scenario on which i need to toggle div on link click. But here catch is that we have links with *same class [to click] and same class[to open/toggle]

Toggle is working fine but i need

  • "Toggle my text" has opened next "textBox"
  • Now if user has clicked on "Toggle my text2" then
    • "textbox" of "Toggle my text" shall be closed[not working currently]
    • "textbox" of Toggle my text2 shall be opened.[working currently]

and vice versa.

Here is JS fiddle link

Fiddle Here

Some of Code is as below:

$(function () {
  $(".textBox").hide();
  $('a.clickMe').click(function () {
    $(this).nextAll('div.textBox:first').toggle();
  });
});

You just have to hide the other divs.

 $(function () { $(".textBox").hide(); $('a.clickMe').click(function () { var target = $(this).nextAll('div.textBox:first'); $(".textBox").not(target).hide(); target.toggle(); }); }); 
 a{cursor:pointer} 
 <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script> <a class="clickMe">Toggle my text</a> <br /> <div class="textBox"> - This text will be toggled</div> <br /><br /><br /> <a class="clickMe">Toggle my text2</a> <br /> <div class="textBox"> - This text will be toggled 2</div> 

EDIT: Following your comment, here is how you would do using classes.

 $(function () { // you may want to set the hidden class directly in the html // instead of the line below to avoid the text boxes appearing // before the js executed the first time. $(".textBox").addClass("hidden"); $('a.clickMe').click(function () { var target = $(this).nextAll('div.textBox:first'); $(".textBox").not(target).addClass("hidden"); target.toggleClass("hidden"); }); }); 
 a { cursor: pointer; } .hidden { display: none; } 
 <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script> <a class="clickMe">Toggle my text</a> <br /> <div class="textBox"> - This text will be toggled</div> <br /><br /><br /> <a class="clickMe">Toggle my text2</a> <br /> <div class="textBox"> - This text will be toggled 2</div> 

http://jsfiddle.net/xe18wusw/6/

$(function () {
$(".textBox").hide();
$('a.clickMe').click(function () {
    var thisElem = this;
    var isVisibe = $(thisElem).nextAll('div.textBox:first').is(":visible");
    $(".textBox").each(function(i,elem){
        console.error(thisElem,elem)
        if(thisElem!==elem){
            $(elem).hide();
        }
    });
   // if()
    $(thisElem).nextAll('div.textBox')[isVisibe ? "hide" : "show"]();
    $(thisElem).nextAll('.clickMe:first').nextAll("div.textBox").hide();
   });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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