简体   繁体   中英

How can I create a comma-separated list of IDs in JavaScript?

So I have a <ul> that contains <li> elements, and I'd like to grab the IDs of these out and pass them on in a querystring to another page.

Like so:

<ul id="myList">
   <li id="first">First</li>
   <li id="second">Second</li>
   <li id="third">Third</li>
</ul>

into

first,second,third

Is there a neat way to do this? I've jQuery, so my brute-force probably-not-very-good-approach is to iterate using each() and build it that way. A bit scruffy, I think.

A short and neat way using .map :

var ids = $("#myList li").map(function() {
    return this.id;
}).get().join(",");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM