Home > Backend Development > PHP Tutorial > 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

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2023-03-02 14:42:02
Original
1400 people have browsed it

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>
Copy after login

When binding the event, pass this in, onclick="choose(this)"

function choose(x){

<code>alert(x.getAttribute("data-name"))</code>
Copy after login

}

$(this).attr('data-name');

Get attributes - attr()
jQuery attr() method is used to get attribute values.

$('#toy').attr('data-name');

Related labels:
Statement of this Website
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
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template