开发者

Programmatically set up a slideToggle for any number of items

I have the following jQuery code, which works fine:

$(document).ready(function () {
    $('#link1').click(function () {
    $('.data1').slideToggle('slow');
    });
    $('#link2').click(function () {
    $('.data2').slideToggle('slow');
    });
    /* so on a so forth */
});

link1 is an ID that I have for a div tag around a hyperlink. Data1 is an ID for another div tag for content that I want shown if the user clicks on the hyperlink. My question is, if I have 50 or even 100 hyperlinks and content that goes with each of those, it would be cumbersome to list that code 50 or 100 times with each ID listed separately.

How can I do this programmatically? I tried setting up a for loop, but I probably had the syntax screwed up. I also 开发者_Go百科tried using the each() function.

Any help would be greatly appreciated.


The easiest way would be to define a class for these, and also a better ID. I would say something like this:

<a href="#" id="link_1" class="toggle_link">Link 1 Text</a>
<div class="data_1">Fos</div>

<a href="#" id="link_2" class="toggle_link">Link 2 Text</a>
<div class="data_2">Fos Fos</div>

Then you can easily attach your events like:

$('.toggle_link').click(function () {
  var name=this.id.split('_');
  $('.data_'+name[1]).slideToggle('slow');
});

I put the underscore there to make it easy to find where the ID starts. I would not say this is production-ready code yet, but can give you the idea.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜