i trying use .data value out of attribute.
html
<div class="like" data-postid="903282304865jh"> </div> js
$(".like").click(function(event){ var postid = $(event.target).data('postid'); console.log(postid); }); i undefined returned in console. whats going on here?
use $(this) instead of $(event.target):
var postid = $(this).data('postid'); your code works if there not other elements in div.
also consider comparing target.event this:
event.target
the dom element initiated event. read more
this
in jquery, element being acted upon passed function parameter of jquery function this. can made jquery element object using $(this). read more
example
your code becomes:
$(".like").click(function(event){ var postid = $(this).data('postid'); alert(postid); }); as html example can following:
<div class="like" data-postid="903282304865jh"><i>a</i> test</div>
Comments
Post a Comment