Equivalent of $(this) in native javascript

坚强是说给别人听的谎言 提交于 2019-12-05 17:47:41

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")

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/

You could use the below code to get an almost equivalent of $(this)

document.querySelector("#myId").addEventListener("click", function(e) {
  console.log(this);    //Prints the Element
  $this = new Array(e.target);
  console.log($this);   //Prints the Object
});

PEN

Hope this helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!