Home >Backend Development >PHP Tutorial >javascript - How to get the current data-name from the onlick event of a tag
Example code: http://codepen.io/hj624608494...
The problem arises from the point of this. This always points to the object when the function is executed.
<code>function choose(){ alert($(this).data('name')); // undefind 因为choose函数的this指向的是window } function choose2(){ $('#J_a').click(function(){ // 这个点击事件的匿名函数的this 指向的是 $('#J_a') 这个对象 alert($(this).data('name')); }) } choose2()</code>
When binding the event, pass this in, onclick="choose(this)"
function choose(x){
<code>alert(x.getAttribute("data-name"))</code>
}
$(this).attr('data-name');
Get attributes - attr()
jQuery attr() method is used to get attribute values.
$('#toy').attr('data-name');