using jquery to find .each on .attr() with regex

人盡茶涼 提交于 2020-01-06 20:08:01

问题


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)]'));
    });
 }
  1. How would I insert the (i)
  2. Is it possible to do a search on a partial regex instead of using (i), (info*) infoA, infoB
  3. 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!