JQuery的.click()如何在幕后工作? [英] How does JQuery's .click() work behind the scenes?

查看:102
本文介绍了JQuery的.click()如何在幕后工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题是出于好奇。我想知道如何jquery的.click()在幕后工作。

This question is just out of curiosity. I want to know how jquery's .click() works behind the scenes.

例如,如果我创建一个按钮:

For instance if I create a button:

<input type="button" id="myButton" value="Click me!" />

然后我有以下jquery代码:

Then I have the following jquery code:

$('#myButton').click( function() {
    alert("I have been clicked.");
});

jquery如何让它点击按钮时调用函数?

How does jquery make it so that my function is called when the button is clicked?

起初我以为会将 onClick =属性添加到按钮的标签中,但是当我用Firebug检查了页面我刚刚看到:

At first I thought it would add the onClick="" attribute to the button's tag, but when I inspected the page with Firebug I just saw:

<input type="button" id="myButton" value="Click me!" />

那么jquery在幕后做什么?

So what does jquery do behind the scenes?

推荐答案

这将取决于浏览器。

如果您使用的浏览器支持 addEventListener(),他们将添加一个处理程序。

If you're using a browser that supports addEventListener(), they'll add a handler using that.

虽然我很确定他们实际上附加了一个第一个修复/标准化事件对象,然后检查DOM元素的 jQuery12345 ... 属性并查找处理程序在 jQuery.cache 并调用它。

Although I'm pretty sure they're actually attaching a function that first repairs/normalizes the event object, then checks the DOM element for the jQuery12345... property and looks up the handler in jQuery.cache and invokes it.

如果您将元素记录到控制台,您会看到属性看起来像:

If you log your element to the console, you'll see a property that looks something like:

jQuery1296081364954: 1

然后,如果您从 jQuery.cache 将该号码记录到控制台,您将看到相关数据。 >

Then if you log that number to the console from jQuery.cache, you'll see the associated data.

console.log(jQuery.cache[1]);

...这将给出一个这样的结构:

...which will give a structure something like this:

{
   events:{
      click:[
         { /* object containing data relevant to the first click handler */ }
      ]
   },
   handle:{ /* this may be what initially gets called. Not sure. */ }
}

由于jQuery正常化事件对象,只需为您分配一个处理程序并调用它即可。我相信它也是通过缓存来完成的,以避免旧版浏览器中的内存泄漏。

Because jQuery does normalize the event object, it isn't quite as simple as just assigning a a handler for you and calling it. I believe it is also done with the cache in order to avoid memory leaks in older browsers.

这篇关于JQuery的.click()如何在幕后工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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