【问题标题】:Simple Javascript to mimic jQuery behaviour of using this in events handlers简单的 Javascript 来模仿在事件处理程序中使用 this 的 jQuery 行为
【发布时间】:2011-02-07 13:02:17
【问题描述】:

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

在 jQuery 中你可以这样做:

$('#some_link_id').click(function() 
{
   alert(this.tagName); //displays 'A'
})

有人可以笼统地解释一下(无需您编写代码)他们如何获得将事件的调用者 html 元素(此特定示例中的链接)传递到 this 关键字?

我显然试图在 jQuery 代码中查看 1st,但我无法理解一行。

谢谢!

更新: 根据 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         
}

然后现在通过一个简单的调用,我们模拟了在事件处理程序中使用 this 的 jQuery 行为

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

你认为有什么错误或我误解的东西太肤浅了吗?

【问题讨论】:

  • FF看起来不错,好久没写IE特有的事件处理了,不过如果能用就万事大吉了! :)

标签: javascript events event-handling this dom-events


【解决方案1】:

在 Javascript 中,您可以通过编程方式调用函数并告诉它this 应该引用什么,并使用Function 中的callapply 方法传递一些参数。函数在 Javascript 中也是一个对象。

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

例如:

function alertElementText() {
    alert(this.text());
}

这将调用上下文 (this) 对象上的文本函数,并提醒它的值。现在我们可以调用该函数并将上下文 (this) 设为 jQuery 包装的元素(这样我们就可以直接调用 this 而无需使用 $(this)

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

使用callapply 调用函数之间的区别是微妙的。对于call,参数将按原样传递,而对于apply,它们将作为数组传递。在 MDC 上阅读有关 applycall 的更多信息。

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

document.getElementById("someId").onclick = function() {
    // this refers to #someId here
}

【讨论】:

  • Hmmmm...那看起来很简单。我根据您的回答更新了问题,我想听听您的反馈。
猜你喜欢
  • 2011-08-09
  • 2021-04-10
  • 2013-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-26
  • 2016-04-07
  • 2011-03-28
相关资源
最近更新 更多