Question

I'm trying to consolidate down some of the Javascript on my website into a common .js file that's shared across the whole site, instead of having to write out everything in the <head> tag on the page each time.

One of the problems I'm having is that I have multiple pages with a different number of JQuery UI accordion widgets on each page. For instance, one page will have two accordions, and another will have 7, and another will have 5.

Now, I can have the accordion method initialize whatever the maximum number of accordions I might need for the page with the most accordions on it, and just not use the extra IDs that are generated, but that seems like a really poor and inefficient way to code things. If there a way I can use a loop in Javascript to see how many accordion IDs are on the page and create only the number of accordions that I need? For instance, if I have:

<div id="acc1">
     <!-- the accordion content here-->
</div>
<div id="acc2">
     <!-- the accordion content here-->
</div>
<div id="acc3">
     <!-- the accordion content here-->
</div>
<div id="acc4">
     <!-- the accordion content here-->
</div>

Then my the accordion method in the document.ready event should know to automatically generate 4 accordions:

$("#acc1, #acc2, #acc3, #acc4").accordion();

What's the most effective way, if possible, that I can do this with a loop?

Était-ce utile?

La solution

You don't need a loop for that.

Just give each accordion a common class, say class="accordion", and then:

$(".accordion").accordion();

DEMO

Autres conseils

Using the current markup you could do:

$( "div[id^='acc']" ).accordion();

http://api.jquery.com/attribute-starts-with-selector/

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top