简单的javascript来模仿在事件处理程序中使用它的jQuery行为

Mar*_*aio 6 javascript events this event-handling javascript-events

这不是关于jQuery的问题,而是关于jQuery如何实现这样的行为.

在jQuery中你可以这样做:

$('#some_link_id').click(function() 
{
   alert(this.tagName); //displays 'A'
})
Run Code Online (Sandbox Code Playgroud)

有人可以用一般术语解释(不需要你编写代码)他们如何获得将事件的调用者html元素(在这个特定示例中的链接)传递给this关键字?

我显然试图在jQuery代码中看第一,但我无法理解一行.

谢谢!

更新: 根据Anurag的回答,我决定在这一点上发布一些代码,因为它似乎比我想象的更容易编码:

function AddEvent(html_element, event_name, event_function)
{      
   if(html_element.attachEvent) //IE
      html_element.attachEvent("on" + event_name, function() {event_function.call(html_element);});
   else if(html_element.addEventListener) //FF
      html_element.addEventListener(event_name, event_function, false); //don't need the 'call' trick because in FF everything already works in the right way         
}
Run Code Online (Sandbox Code Playgroud)

然后现在通过简单的调用我们模仿在事件处理程序中使用它的jQuery行为

AddEvent(document.getElementById('some_id'), 'click', function()
{            
   alert(this.tagName); //shows 'A', and it's cross browser: works both IE and FF
}); 
Run Code Online (Sandbox Code Playgroud)

你认为有任何错误或我误解的事情以一种过于肤浅的方式采取一切吗?

Anu*_*rag 2

在 Javascript 中,您可以以编程方式调用函数并告诉它this应该引用什么,callapply使用Function. 函数在 Javascript 中也是一个对象。

jQuery 迭代其结果中的每个匹配元素,并调用click该对象上的函数(在您的示例中),将元素本身作为上下文或this该函数内部引用的内容传递。

例如:

function alertElementText() {
    alert(this.text());
}
Run Code Online (Sandbox Code Playgroud)

这将调用上下文(this)对象上的文本函数,并警告它的值。现在我们可以调用该函数并使上下文(this)成为 jQuery 包装的元素(因此我们可以this直接调用而无需使用$(this).

<a id="someA">some text</a>
alertElementText.call($("#someA")); // should alert "some text"
Run Code Online (Sandbox Code Playgroud)

call使用函数或apply调用函数之间的区别很微妙。Withcall参数将按原样传递,并且 withapply它们将作为数组传递。了解有关申请致电MDC 的更多信息。

同样,当调用 DOM 事件处理程序时,this已经指向触发该事件的元素。jQuery 只是调用您的回调并将上下文设置为元素。

document.getElementById("someId").onclick = function() {
    // this refers to #someId here
}
Run Code Online (Sandbox Code Playgroud)