简体   繁体   中英

Access rel attribute using this keyword javascript

Please check the JSFIDDLE , the rel attribute in the alert comes out as 'undefined' :

var ItemTypeArray = $('input[name^=ItemType]:checked').map(function(){


alert(this.id + '  , r= ' + this.rel);  

return this.rel + '--' + this.value;

}).get().join(",");  

Also , this function gives a string , but I need an array to be constructed to post it.

There's no such attribute called rel on an input (there is on a link tag however). You should really use data attributes instead:

<input id="SOLD[1]" value="1" name="ItemType[1]" type="radio" data-rel="1">
<input id="PURCHASED[1]" value="2" name="ItemType[1]" type="radio" checked="checked" data-rel="1">

Then you can do:

var ItemTypeArray = $('input[name^=ItemType]:checked').map(function () {
    alert(this.id + '  , r= ' + $(this).data("rel"));
    return $(this).data("rel") + '--' + this.value;
}).get().join(",");

Or to return what you stated in comments (an array), you can do:

var ItemTypeArray = [];

$('input[name^=ItemType]:checked').each(function () {
    ItemTypeArray.push(this.id + ' = ' + $(this).data("rel"));
});

See HERE

I just included jquery and modified your code as follows. Use $(this).attr('rel') instead of this.rel

    var ItemTypeArray = $('input[name^=ItemType]:checked').map(function () {
        alert(this.id + '  , r= ' + $(this).attr('rel'));
        return this.rel + '--' + this.value;
}).get().join(",");

Here is the jsfiddle

try

 $(this).attr("rel")

this will get you an attribute value named 'rel'

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