开发者

Determine number of divs with jQuery

I'm using jQuery Tools (http://flowplayer.org/tools/index.html) to create tooltips, I've created a js-file that holds the following lines:

$("div#example-0").tooltip('#example-0-tooltip');
$("div#example-1").开发者_开发百科tooltip('#example-1-tooltip');
$("div#example-2").tooltip('#example-2-tooltip');
$("div#example-3").tooltip('#example-3-tooltip');

etc.

This works fine if there's a known number of example-divs, however I would like this to work with an unknown number of example-divs.

Basically I would like my jQuery to be able to read the DOM-tree and determine how many example-divs there is and somehow loop through them all and add the tooltip.

Anyone know how to do this?


Use the starts with attribute matcher and iterate. Grab the id from the current element and invoke the tooltip.

$('div[id^=example-]').each( function() {
    $(this).tooltip( '#' + $(this).attr('id') + '-tooltip' );
});

Or, if they each had the same class in addition to unique ids.

$('div.exampleClass').each( function() {
    $(this).tooltip( '#' + $(this).attr('id') + '-tooltip' );
});

Or if, as @Savageman suggests, you can get away with reusing the same named DIV for the tooltip (and use a class to mark all divs that need a tooltip).

$('div.exampleClass').tooltip('#exampleTooltip');


Give them all the same class so that you can just do

$('div.classname').tooltip(...);


This returns element number :

$('element').size();


Put a certain class to all divs. Essential code will remain the same.

Ex:

<div id="1" class="tooltip">
</div>

<div id="2" class="tooltip">
</div>
<div id="3" class="tooltip">
</div>
<div id="4" class="tooltip">
</div>

and the code:

$("div.tooltip").tooltip('#example-0-tooltip');


not sure if this helps, but there's a tooltip plugin for jquery which can use the title attribute of a tag to generate a tooltip. It does it automatically, so you wouldn't have to set a statement for each, just have a title assigned to the div.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜