简体   繁体   English

脚本生成元素上的jquery click事件

[英]jquery click event on script generated element

I have this script: 我有这个脚本:

<script>
    $(document).ready(function() {
       $('.block-link').click(function() {
          $('body').addClass("gallery-on");
       });

       $('body').delegate('.ps-toolbar-close', 'click', function() {
          $('body').removeClass("gallery-on");
          });
       });
</script>

The script is supposed to add the class .gallery-on to the body when i click on any .block-link . 当我单击任何.block-link时,脚本应该将.gallery-on类添加到body
The .ps-toolbar-close element is generated through a plugin (pretty good btw!) that create a modal lightbox when any .block-link is clicked. .ps-toolbar-close元素是通过插件 (相当不错的btw!)生成的,该插件会在单击任何.block-link时创建一个模式灯箱。

The first part of the script is working, the second is supposed to remove the .gallery-on class from the body, but it just close the lightbox and let the body class where it is. 该脚本的第一部分正在工作,第二部分应该从主体中删除.gallery-on类,但它只是关闭灯箱,然后将主体类放置在原处。

What am i doing wrong? 我究竟做错了什么? i'm a beginner with javascript and jquery unfortunately.. 我很不幸,是使用javascript和jquery的初学者。

My best guess is that since .ps-toolbar-close is not yet present in the document when the page loads, no click handler is placed for the second part of the script, though i thought that .delegate() was able to handle not yet existing elements, am i wrong? 我最好的猜测是,由于页面加载时文档中尚不存在.ps-toolbar-close ,因此脚本的第二部分没有放置任何单击处理程序,尽管我认为.delegate()能够处理现有元素,我错了吗?

Thanks for any help! 谢谢你的帮助!

Most likely this is due to an interesting property of the delegate method. 这很可能是由于委托方法的一个有趣的属性。 From the jQuery documentation: 从jQuery文档中:

Additional Notes: 补充笔记:

Since the .live() method handles events once they have propagated to the top of the document, it is not possible to stop propagation of live events. 由于.live()方法一旦将事件传播到文档顶部便会对其进行处理,因此无法停止实时事件的传播。 Similarly, events handled by .delegate() will propagate to the elements to which they are delegated; 类似地,由.delegate()处理的事件将传播到它们所委派的元素; event handlers bound on any elements below it in the DOM tree will already have been executed by the time the delegated event handler is called. 到委托事件处理程序被调用时,绑定到DOM树中其下任何元素的事件处理程序将已经执行。 These handlers, therefore, may prevent the delegated handler from triggering by calling event.stopPropagation() or returning false. 因此,这些处理程序可以通过调用event.stopPropagation()或返回false来阻止委托处理程序触发。

The close method for the modal dialog is being attached lower down in the DOM and is being called prior to your body handler and preventing your handler firing correctly. 模态对话框的close方法在DOM中向下附加,并在主体处理程序之前被调用,并防止处理程序正确触发。

Try binding to the close event for the dialog and removing the class there. 尝试绑定到对话框的close事件 ,然后在其中删除类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM