Selecting all elements
This should be really simple but I'm a javascript/jQuery rookie, so here we go:
With the following code I can select a certain element
var user = $(".ui-selected .user-name").html();
But if there are multiple elements with the above classes, only the first value get开发者_开发问答s selected. What I would like to accomplish is a variable with all the elements seperated by a , like: user1,user2,user3 ... etc. Any help would be greatly appreciated, thanks in advance!
You can use .map()
to get an array of values, then .join()
them to a string, like this:
var usersString = $(".ui-selected .user-name").map(function() {
return $(this).html(); //or this.innerHTML
}).get().join(',');
Edit: here's a demo, you can tweak the join, etc if needed.
You can use .each() to go through each one:
$(".ui-selected .user-name").each( function(){
var user = $( this ).html();
// do stuff
} )
You can do something like this:
var myElements = "";
$(".ui-selected .user-name").each( function(){
myElements += $(this).html() + ",";
} )
精彩评论