且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Javascript - $(document).on(" click"," selector",function ...)之间的差异;和$(" selector")。on(" click",function ....);

更新时间:2022-12-08 22:37:39

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