简体   繁体   中英

Using JQuery's .attr() When Selector Returns Multiple elements

I am trying to pull 2 pieces of data from each of several fields. All the fields have been given the same "name" so as to allow them to be referenced easily.

 <input type="text" name="common_name" data-X='ABC'>

The first piece of data I am pulling is their values, which does seem to be working. My issue is when I try to use attr() . It just stops dead in the water at that point.

var length = $('[name=common_name]').size();
for(var i=0; i < length; i++){
    var value = parseInt($('[name=common_name]').get(i).value); //doesn't kill the script            
    var dataX = $('[name=common_name]').get(i).attr('data-X'); //Script is killed here
 }

Since I'm not having issues with using attr() in general when the selector is selecting the element based on an id, I would think the issue has to do with the fact that in this case multiple elements are being returned by jQuery. What I am confused by is that I thought that get(#) is supposed to grab a specific one…in which case I don't see what the problem would be. (After all, using get(#) DOES work when I use val() ).

So…why doesn't attr() work here?

.get() returns a dom element reference which does not have the .attr() method, so you can use the .eq() method which will return a jQuery object

var length = $('[name=common_name]').size();
for (var i = 0; i < length; i++) {
    var value = parseInt($('[name=common_name]').eq(i).val()); //doesn't kill the script            
    var dataX = $('[name=common_name]').eq(i).attr('data-X'); //Script is killed here
}

The correct way to iterate over an jQuery object collection is to use the .each() method where the callback will be invoked for each element in the jQuery collection

$('[name=common_name]').each(function () {
    var $this = $(this);
    var value = parseInt($this.val()); //or this.value         
    var dataX = $this.attr('data-X'); //or $this.data('X')
})

Suppose the html is like this

 <input type="text" name="common_name" data-X='ABC'>
 <input type="text" name="common_name" data-X='DEF'>
 <input type="text" name="common_name" data-X='GHI'>

Now the script part

$('input[name="common_name"]').each(function() {
     var el = $(this);
     text_val = el.val();
     data = el.attr('data-X');
     console.log(text_val);
     console.log(data);
});

attr is a jquery fn, should call by jquery object

use like this

$('[name=common_name]').attr('data-X')

so try

dataX = $($('[name=common_name]').get(i)).attr('data-X');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM