获取被点击元素的属性值 [英] get value of an attribute of the clicked element

查看:113
本文介绍了获取被点击元素的属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<ul id='langs'>
   <li data-val='en'>english</li>
   <li data-val='fr'>francais</li>
   <li data-val='it'>italiano</li>
</ul>

当用户点击其中任何< li> 我想 alert()它的data-val属性值

when the user clicks on any of these <li> I want to alert() it's data-val attribute value

任何人都知道怎么做?

推荐答案

原始答案 - 2011



Original answer - 2011

$('li').click(function () {
    alert($(this).data('val'));
});

参见 DEMO

保持请注意,如果您想使用ES6 箭头功能语法,你不能使用这个而你需要使用 e.currentTarget ,其中 e 是作为事件处理程序的第一个参数传递的事件对象:

Keep in mind that if you want to use the ES6 arrow function syntax, you cannot use this and you need to use e.currentTarget instead, where e is the event object passed as the first parameter to the event handler:

$('li').click(e => alert($(e.currentTarget).data('val')));

参见 DEMO

这篇关于获取被点击元素的属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆