问题
I am sure this has been answered before, but I cant find the correct search terms.
I would like to use jquery[1.3.2] .each() function to search an object for a set name+var(i) info1="value1", info2="value2"
the (i) val is unknown for the function, could be 0+n
I am parsing the id to the function, so my questions are
function findInfos(hostId){
$($('#'+hostId).attr('[info]')).each(function(){
alert($(this).attr('[info(i)]'));
});
}
- How would I insert the (i)
- Is it possible to do a search on a partial regex instead of using (i), (info*)
infoA, infoB
- given the object ID will be passed to the function and unknown what is the correct structure use of .each()
I did take a look at http://stackoverflow.com/questions/4606133/jquery-each-and-attr-functions
but could not figure out how to limit the .each() to the passed ID.
thx Art
回答1:
It looks like you're looking at a single element with multiple attributes, and you want to do something with the attributes that match a certain regex, like /^info\d$/
. If so, what you want to do is cycle through the DOM element's attributes
NamedNodeMap
:
var el = $('#foo');
var attributes = el[0].attributes;
$.each(attributes,function(i,attr){
var name = attr.nodeName;
var val = attr.nodeValue;
var regex = /^info\d$/;
if(name.match(regex)) {
//Do something with your matched attributes
}
});
Tested with jQuery 1.3.2
jsFiddle DEMO
回答2:
If I'm not mistaken, I believe you want something like this:
function findInfos(hostId) {
$('#' + hostId).attr('[info]').each(function(i) {
alert($(this).attr('[info'+i+']'));
});
}
Also, avoid assigning the same id to multiple objects, as this can result in some nasty errors.
来源:https://stackoverflow.com/questions/11363585/using-jquery-to-find-each-on-attr-with-regex