[英]Why does jQuery behave differently than javascript?
I'm new to jQuery and wrote the following code. 我是jQuery新手,并编写了以下代码。 Strangely, the jQuery code somehow works even after the time delay.
奇怪的是,即使经过时间延迟,jQuery代码还是可以正常工作。 alert() gets called onclick after the time delay.
时间延迟后,alert()被称为onclick。 The same thing in javascirpt with .addEventListener() would give error since the element doesn't exist.
javascirpt中带有.addEventListener()的同一事物将产生错误,因为该元素不存在。 Can someone explain me how and why jQuery does this?
有人可以解释一下jQuery为何以及为什么这样做吗?
<div id="outerId" class="outerHolder">
<div class="innerHolder"></div>
</div>
JS Code: JS代码:
$("#outerId").on("click touchstart", "#newTag", function (e) {
alert("OK");
});
setTimeout(function() {
var tag = '<div id="newTag">Hello World</div>';
$("#outerId").append(tag);
}, 5000);
Here is a jsFiddle of the same: https://jsfiddle.net/jb6pmovb/ 这是相同的jsFiddle: https ://jsfiddle.net/jb6pmovb/
If you are wondering how the click works on an element which is not there at the time of page load, then that's because you are attaching the listener on the outerDiv and using .on
如果您想知道单击如何在页面加载时不存在的元素上起作用,那是因为您要将侦听器附加到externalDiv上并使用
.on
Check out this for the difference between using .on
and .click
看看这对两者的区别
.on
和.click
My guess is that your query is about the way on()
is binding to to the object. 我的猜测是您的查询是关于
on()
绑定到对象的方式。 When on()
is first ran, #newTag
does not exist, so you might be wondering why it still triggers when appended after a delay. 首次运行
on()
, #newTag
不存在,因此您可能想知道为什么在延迟后附加时仍触发它。
This is because #outerId
is the object being bound to, which does exist the time on()
is called. 这是因为
#outerId
是要绑定的对象,在on()
调用时确实存在。 When you append #newTag
, it doesn't alter the outer binding, it simply looks over the children when it is clicked. 当您附加
#newTag
,它不会更改外部绑定,只在单击它们时才查看子项。
With regular js I assume you are using addEventListener
, which requires you bind the event to the specific object. 对于常规js,我假设您正在使用
addEventListener
,这需要将事件绑定到特定对象。 If you do try and use that directly on #newTag
before it exists, it obviously won't work. 如果您确实尝试在
#newTag
上直接使用它,则显然将无法使用。
You can see by the docs for on()
: 您可以通过文档查看
on()
:
selector
选择器
Type: String A selector string to filter the descendants of the selected elements that trigger the event.
类型:字符串一个选择器字符串,用于过滤触发事件的所选元素的后代。 If the selector is null or omitted, the event is always triggered when it reaches the selected element.
如果选择器为null或省略,则事件在到达所选元素时始终被触发。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.