等价于本机javascript中的$(this) [英] Equivalent of $(this) in native javascript
问题描述
我想向按钮添加事件侦听器,并且我在纯粹使用javascript编码方面还相对较新,所以我不知道$this
I wanted to add and event listener to a button and I am still relatively new on coding purely on javascript, so I don't know what are the native equivalent of $this
在我的代码中
// the markup
<ul class="menu">
<li><a href="#" data-something="value">text</a></li>
<li><a href="#" data-something="value2">text2</a></li>
</ul>
var menu = document.querySelector(".menu");
menu.addEventListener("click", function(){
// console.log $(this).val
// what I wanted is to get that data-attribute of the clicked item
});
推荐答案
在事件处理程序this
中,它将表示事件处理程序绑定到的元素.您将没有jQuery提供的所有实用程序功能.因此,在您的示例中,您将无法使用this.data("something")
Within the event handler this
will represent the element to which the event handler is bound. You will not have all of the utility functions provided by jQuery. So in your example you will not be able to retrieve the data attribute by using this.data("something")
要检索自定义属性的值,代码必须将事件传递给函数.在示例中的event
或e
中,target
属性将包含触发事件的元素,由于事件的传播,该元素可能并不总是与事件处理程序绑定的元素.使用getAttribute
方法检索自定义属性的值.另外,请勿将自定义属性设置为大写,因为html规范不允许这样做,并且会创建无法访问的属性.
To retrieve the value of the custom attribute the code must pass the event to the function. From the event
or e
in the example, the target
property will contain the element that triggered the event, which may not always be the element to which the event handler was bound, due to the propagation of events. Use the getAttribute
method to retrieve the value of custom attribute. Also refrain from making the custom attributes upper case as the html specifications do not allow for this and will create inaccessible attributes.
var menu = document.querySelector(".menu");
menu.addEventListener("click", function(e){
alert(e.target.getAttribute("data-something"));
});
JS Fiddle:: http://jsfiddle.net/pjcvB/
这篇关于等价于本机javascript中的$(this)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!