简体   繁体   English

jQuery Click事件未触发div

[英]jQuery click event not firing for div

I don't understand why this isn't working. 我不明白为什么这行不通。 I have a table that includes a div and an image in the header. 我有一个表,其中包含div和标题中的图像。 When I click on this, I want to fire the click event via a jQuery function. 当我单击它时,我想通过jQuery函数触发click事件。 Here is a screenshot of the HTML: 这是HTML的屏幕截图:

在此处输入图片说明

And here is the jQuery function: 这是jQuery函数:

$(document).ready(function () {
    console.log('ready');

    $('#add_external_link').on('click',function(){
        alert('clicked');
    });
});

I believe that the element is in the DOM before the event is bound. 我相信该元素在事件绑定之前就位于DOM中。 The tail of the HTML looks like this (it's the 'external_link_dialog.js' file that contains the jQuery language from above): HTML的尾部看起来像这样(它是'external_link_dialog.js'文件,其中包含上面的jQuery语言):

        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
        <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
        <script src="js/jquery.dlmenu.js"></script>
        <script src="js/external_link_dialog.js"></script>

    </body>
</html>

My console output shows ready as soon as the page is loaded. 页面加载后,我的控制台输出显示ready However, when I click that <div> , nothing happens. 但是,当我单击该<div> ,没有任何反应。 I see no errors, no console output, and of course no alert. 我没有看到错误,没有控制台输出,当然也没有警报。 Can anyone see what I am doing wrong? 谁能看到我在做什么错? I've been at this for hours, and am out of ideas. 我已经在这里呆了几个小时了,没有想法。 Thank you! 谢谢!

Depending on your CSS, the div may actually be smaller than the image you're trying to click on. 根据您的CSS,div可能实际上小于您要单击的图像。

Try setting your target to the following: 尝试将目标设置为以下内容:

$('#add_external_link img').on('click', function(){
    alert('clicked');
});

I guess that you are appending the div after the document.ready . 我想你是在document.ready之后追加div。 If you are adding that add_external_link div dynamically, you should attach the .on("click function after appending that div . 如果要动态添加add_external_link div,则应附加div 之后附加.on("click函数。

If the div is not added dynamically, then try adding a timeout 如果未动态添加div,请尝试添加超时

$(document).ready(function () {
    console.log('ready');
    setTimeout(function(){
      $(document).on('click','#add_external_link',function(){
          alert('clicked');
      });
   },1000);
});

Try delegating to document or the closest static element. 尝试委派给文档或最接近的静态元素。

$(document).on('click','#add_external_link',function(){
    alert('clicked');
});

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

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