[英]jquery multiple show/hide buttons
I am trying to convert a lot of JavaScript to jQuery and I have a task that I believe has a simple jQuery shortcut, but I don't know what it is and I haven't been able to find an example. 我正在尝试将许多JavaScript转换为jQuery,我有一个任务,我相信它有一个简单的jQuery快捷方式,但我不知道它是什么,而且我无法找到示例。
I have a page with many toggled divs. 我的页面上有很多切换的div。 They are in the form that follows where ### is a unique integer for each pair.
它们采用以下形式,其中###是每对的唯一整数。
<button class='togglebutton' onclick="toggle('div###');">+</button>
<div id='div###'>...some text...</div>
I'd assume the shortcut is something like: 我认为快捷方式是这样的:
$('.togglebutton').onclick(function() {
var divid = '#div'+?????;
$(divid).toggle();
});
My theory... if I give each button an id, such as 'button###', then I can use substring to get the value after the word 'button', something like: 我的理论...如果给每个按钮一个ID,例如“ button ###”,那么我可以使用子字符串来获取单词“ button”之后的值,例如:
$(this).id().substring(6,3);
Obviously, that didn't work. 显然,这没有用。 So, I figured that I should ask if there is a simple shortcut in jQuery to pair a showhide button with a separate div.
所以,我想我应该问一下jQuery中是否有一个简单的快捷方式来将一个showhide按钮与一个单独的div配对。
You may want to do this no matter where your div locates http://jsfiddle.net/tg5op333/25/ 无论您的div位于http://jsfiddle.net/tg5op333/25/,您都可能希望这样做
HTML HTML
<button class='togglebutton' data-id="1">+</button>
<div id='1' style="display:none">...some text...</div>
<button class='togglebutton' data-id="2">+</button>
<div id='2' style="display:none">...some text...</div>
<button class='togglebutton' data-id="3">+</button>
<div id='3' style="display:none">...some text...</div>
<button class='togglebutton' data-id="4">+</button>
<div id='4' style="display:none">...some text...</div>
JS: JS:
$('.togglebutton').click(function() {
$("#"+ $(this).data('id')).toggle();
});
If the HTML is ordered like you show in your question, then use: 如果按照问题中显示的顺序排列HTML,请使用:
$('.togglebutton').click(function() {
$(this).next().toggle();
});
$('.togglebutton').click(function() { $(this).next().toggle(); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <button class='togglebutton'>+</button> <div id='div1'>...some text...</div> <button class='togglebutton'>+</button> <div id='div2'>...some text...</div> <button class='togglebutton'>+</button> <div id='div3'>...some text...</div>
Two ways: 两种方式:
1) You can use some common class attribute to all dives and select all using that. 1)您可以对所有潜水使用一些通用的类别属性,并使用所有属性进行选择。
Or 要么
2) Or else you can use this wildcard selector : 2)否则,您可以使用此通配符选择器:
$("[id^=div]")
It gives you all divs whose id starts with div. 它为您提供了所有以div开头的div。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.