开发者

Javascript using Jquery! looping and printing value

Suppose I have this:

<div id="apple" class="fruit"&g开发者_JAVA百科t;</div>
<div id="orange" class="fruit"></div>
<div id="grape" class="fruit"></div>
<div id="pear" class="fruit"></div>

How do I write a javascript function that can loop and print out all the fruit IDs with class "fruit"? Using JQuery.


$('div.fruit').each(function(){
 //will loop through all divs with the class fruit.
 $(this).attr('id'); //will give you the id of the current div
});


As printed out as comma separated list (ids is an array of the ids).

var ids = $.map($('div.fruit'), function(e) {
    return e.id;
});
document.write(ids.join(','));

Working Demo - click on the output tab to see the output.

Using the following would cater for there being <div class="fruit"> with no id

var ids = $.map($('div.fruit'), function(e) {
    return e.id? e.id : null;
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜