Javascript - $(document).on(" click"," selector",function ...)之间的差异;和$(" selector")。on(" click",function ....); [英] Javascript - Difference between $(document).on("click", "selector", function ...); and $("selector").on("click", function ....);

查看:98
本文介绍了Javascript - $(document).on(" click"," selector",function ...)之间的差异;和$(" selector")。on(" click",function ....);的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这两个代码有什么区别?

What is difference between these two codes ?

$(document).on('click', '.close_modal_window', function(){
        alert("window closed");
    });

$('.close_modal_window').on('click', function(){
        alert("window closed");
    });

我花了很长时间才找出我想要关闭模态窗口的原因。
当我使用第一个例子中显示的代码时它可以工作,第二个代码没有,但我不明白为什么。

It took me long time to find out why I want able to close a modal window. When I use code shown in the first example it works, the second one doesn't but I don't understand why.

推荐答案

在你的第一个例子中,你要点击事件来记录,而不是模态窗口本身。您的第一个代码块工作原因是因为即使您以后动态添加元素它也能正常工作。如果您希望第二个代码块也能正常工作,则需要确保在尝试添加单击事件之前已经完全加载了HTML。

In your first example you are putting on click event to document, not to the modal window itself. Reason your first block of code works is because it works even if you add elements dynamically later. If you want your second block of code to work as well, you need to make sure that you already have the HTML fully loaded before trying to add click event.

签出 .on()文档

方式我自己认为,你的第一个代码块将把click事件放在整个文档上。

The way I figure it for myself is that your first block of code is going to put click event on whole document.


  • 每当你点击某处时,它会尝试匹配点击了
    元素。

  • 如果你点击某个地方随机它就不会触发功能,但是如果你点击.close_modal_window,它会在选择器
    上找到一个匹配项,并在那里找到你的启动功能。

你的第二个代码块做同样的事情,但不同。

Your second block of code does the same thing but differently.


  • 第二种方式更快,因为您不会在整页上单击每次
    然后进行匹配。

  • 它会将点击功能直接绑定到.close_modal_window,只有点击它才能点击

  • 但是为了这个工作你必须在页面上已经有
    .close_modal_window的HTML,然后运行这个代码。

同样在在这种情况下,如果添加更多具有相同名称的类,除非再次运行这部分代码,否则它将无法工作,因此如果您计划添加更多具有相同类的HTML元素并单击其上,则必须小心

Also in this case if you add more classes with same name, it will not work unless you run this part of code again, so you have to be careful if you plan on adding more HTML elements with same class and have the click working on it

这篇关于Javascript - $(document).on(" click"," selector",function ...)之间的差异;和$(" selector")。on(" click",function ....);的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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