我正在使用 jQuery 工具 ( http://flowplayer.org/tools/index.html ) 创建工具提示,我创建了一个包含以下几行的 js 文件:
$("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');
等等
如果有已知数量的 example-div,这可以正常工作,但是我希望它可以与未知数量的 example-div 一起使用。
基本上,我希望我的 jQuery 能够读取 DOM 树并确定有多少个 example-div,并以某种方式循环遍历它们并添加工具提示。
有人知道怎么做吗?
最佳答案
使用 starts with 属性匹配器和迭代。从当前元素获取 id 并调用工具提示。
$('div[id^=example-]').each( function() {
$(this).tooltip( '#' + $(this).attr('id') + '-tooltip' );
});
或者,如果它们除了唯一的 ID 之外还具有相同的类。
$('div.exampleClass').each( function() {
$(this).tooltip( '#' + $(this).attr('id') + '-tooltip' );
});
或者,正如 @Savageman 所建议的那样,您可以通过为工具提示重用相同命名的 DIV(并使用一个类来标记所有需要工具提示的 div)来避免这种情况。
$('div.exampleClass').tooltip('#exampleTooltip');
关于jquery - 使用 jQuery 确定 div 的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1745160/