Home  >  Article  >  Backend Development  >  javascript - How to get the current data-name from the onlick event of a tag

javascript - How to get the current data-name from the onlick event of a tag

WBOY
WBOYOriginal
2016-12-01 01:28:001323browse

javascript - How to get the current data-name from the onlick event of a tag

javascript - How to get the current data-name from the onlick event of a tag

Reply content:

javascript - How to get the current data-name from the onlick event of a tag

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');

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn