开发者

jquery - Create a List of all LIs Name's

Given the following block of HTML:

<ul id="taglist">
<li><a name="45" href="开发者_JS百科">Product 1</a></li>
<li><a name="1146" href="">Product 2</a></li>
<li><a name="13437" href="">Product 3</a></li>
<li><a name="51" href="">Product 4</a></li>
</ul>

Is it possible for JQUERY to return a STRING, one variable with the name values:

alert(tagliststring);

Would alert: 45,1146,13437,51

Thanks


You can use the each function:

var names = [];
$('#taglist > li > a').each(function() {
    names.push(this.name);
});
var result = names.join(',');
alert(result);

This way, names will be an array filled with each individual name, and result will be the comma-delimited string that you are looking for.

For more information, see the jQuery documentation.

An even smaller way of doing this is to use jQuery's map function:

var names = $('#taglist > li > a').map(function() { return this.name; }).get();
var result = names.join(',');

The first example will probably be easier for people to read and understand.


Using $.map:

var names = $('#taglist > li > a').map(function() {
  return this.name;
}).get().join(',');
// names will contain the string: "45,1146,13437,51"

The $.map method allows you to pass each element in the current matched set through a function, producing a new jQuery object containing the return values.

After $.map, I use the get method, to obtain a plain JavaScript Array object, where I can finally, call the join method, to generate a string.

Check the above example here.


var output; 
$('li a').each( function() { output += $(this).attr('name') + ','; });

Please note, this will output an extra , at the end.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜