JS:
$('.togglebutton').click(function() {
$("#"+ $(this).data('id')).toggle();
});
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.
I have a page with many toggled divs. 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:
$(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.
解决方案
You may want to do this no matter where your div locates http://jsfiddle.net/tg5op333/25/
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:
$('.togglebutton').click(function() {
$("#"+ $(this).data('id')).toggle();
});
这篇关于jQuery的多个显示/隐藏按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!