I have a table which each td has title, id, and lang attributes. I want all lang of all elements that matched specified title and id. So I tried:
var lossy = $("[title="+hicode+"][id="+hiwidth+"]").attr("lang");
alert(lossy);
But this return only first matched element.
Any idea to return all matched elements in array or even string开发者_如何学JAVA is still OK. Thank you.
try this
var lossy = $("[title="+hicode+"][id="+hiwidth+"]").map(function() { return $(this).attr("lang"); });
alert(lossy);
I'm using the map function that translate all items in an array or array-like object to another array of items. (http://api.jquery.com/jQuery.map/)
You can use the jQuery each()
function to loop through all of the matched elements...
This code defines an array, loops through all of of the matched elements and adds the lang attr to the array.
var results=new Array();
$("[title="+hicode+"][id="+hiwidth+"]").each(function(index){
results[index] = $(this).attr("lang");
});
alert(results);
Also, here is an example that loops through divs and collects the id attr: http://jsfiddle.net/tSmMj/
Hope that helps :)
The standard jQuery function, $(selector)
, does return all matching elements. Your problem is right here:
[id="+hiwidth+"]
You seem to have multiple elements with the same id
attribute and that is not allowed; id
attributes should be unique within each page or you will get undefined behavior. In your case, the browser is only returning the first element that has the id
you're looking for.
So you need to fix your HTML and then fix your selector to match your corrected HTML.
精彩评论