[英]Toggle div on Link[same link class on various] click Jquery
我有一种情况,我需要在点击链接时切换div。 但是这里要注意的是,我们具有*相同类[单击]和相同类[打开/切换]的链接
切换工作正常,但我需要
反之亦然。
这是JS小提琴链接
一些代码如下:
$(function () {
$(".textBox").hide();
$('a.clickMe').click(function () {
$(this).nextAll('div.textBox:first').toggle();
});
});
您只需要隐藏其他div。
$(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>
编辑:在您的评论之后,这是您将如何使用类。
$(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();
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.