jquery multiple show/hide buttons

巧了我就是萌 提交于 2019-12-13 07:26:12

问题


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.


回答1:


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();
    });



回答2:


If the HTML is ordered like you show in your question, then use:

$('.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>



回答3:


Two ways:

1) You can use some common class attribute to all dives and select all using that.

Or

2) Or else you can use this wildcard selector :

$("[id^=div]")

It gives you all divs whose id starts with div.



来源:https://stackoverflow.com/questions/36362067/jquery-multiple-show-hide-buttons

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!