简体   繁体   中英

cant get data From data-n in element

I have this Span :

<span class="span-link" id="2" data-state="True" onclick="javascript: changestate(this.id);">Change State</span>

and in Javascript function I use this code for get value :

function changestate(_thingid) {
    alert(_thingid);
    var tt = $(this).attr("data-state");
    alert(tt);        
}

I getting undefinded for data-state . I test by $(this).data("state") and so getting undefined too .

whats a problems?

That's because this in that context refers to the window object that doesn't have any attribute. You should pass the element to your handler and use it instead of the this keyword.

... onclick="changestate(this);"
function changestate(thing) {
    var id = thing.id;
    var tt = $(thing).attr("data-state");
    alert(tt);
}

Another option is using the passed id for selecting the clicked element which is not a good idea in this case as this already refers to the clicked element.

Since you are using jQuery you could also use it's on method. this keyword in the on callback refers to clicked element.

$('span.span-link').on('click', function() {
     var id = this.id;
     var tt = $(this).data('data-state');
});

You are referencing id, not the object, so change it to this:

var tt = $('#'+_thingid).attr("data-state");

https://jsfiddle.net/6ne5b8zm/

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