问题
I currently have about a dozen html buttons on a page, all with a unique value attribute assigned to them.
Firstly, I want to be able to get the values of these buttons and assign them into an array. Here is my code:
var myArray = [];
$("#buttonID").each(function(){
myArray.push($(this).attr("value"));
});
This works, however only takes the value from the first button, and then ignores the rest, despite them all have the same ID. Have I done something wrong with my .each() ?
Once I have solved that, I would like to then modify the above to only add values of those buttons with ".active" classes on them. i.e a user has selected them.
回答1:
Your selector represents an ID hence the #
this why it picks only one because ID's are supposed to be unique, you need to pick them by class name like .className
after assigning this class name to all of your buttons
have a loonk at this http://www.w3schools.com/jquery/jquery_ref_selectors.asp
回答2:
Let's say you decided to use a common class for your buttons instead of an ID. Example:
<button class="my-class".......
There's a wonderful jQuery method that would put the values of all the button's with this class in an array like so:
var myArray = $('.my-class').map(function() {
return this.value;
})
.get();
来源:https://stackoverflow.com/questions/33458115/put-value-of-buttons-into-array