Javascript 获取被点击元素的属性值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5205411/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
get value of an attribute of the clicked element
提问by Omu
<ul id='langs'>
<li data-val='en'>english</li>
<li data-val='fr'>francais</li>
<li data-val='it'>italiano</li>
</ul>
when the user clicks on any of these <li>I want to alert()it's data-val attribute value
当用户点击其中任何一个时,<li>我想要alert()它的 data-val 属性值
anybody knows how?
有人知道怎么做吗?
回答by rsp
Original answer - 2011
原始答案 - 2011
$('li').click(function () {
alert($(this).data('val'));
});
See DEMO.
见演示。
Update - 2017
更新 - 2017
Keep in mind that if you want to use the ES6 arrow functionsyntax, you cannot use thisand you need to use e.currentTargetinstead, where eis the event object passed as the first parameter to the event handler:
请记住,如果要使用 ES6箭头函数语法,则不能使用,this而需要e.currentTarget改用,其中e将事件对象作为第一个参数传递给事件处理程序的位置:
$('li').click(e => alert($(e.currentTarget).data('val')));
See DEMO.
见演示。
回答by sled
回答by Darin Dimitrov
$('li').click(function() {
alert($(this).attr('data-val'));
});

