【问题标题】:Attaching click event won't work附加点击事件不起作用
【发布时间】:2017-11-08 11:15:46
【问题描述】:

我想将点击事件附加到尚未添加到 DOM 的对象上,例如 here

我使用了code from the answer,但是当我点击任何东西时什么都没有发生。

这是我的 HTML:

<html>
<head>
<script src="resources/js/components/jquery/jquery-3.1.1.min.js"></script>
<script src="file.js"></script>
</head>
<body>
    <a href="#">asl;kdfjl</a>
    <div id="my-button">sdgdf</div>
</body>
</html>

JavaScript 位于这些位置,我可以在 Chrome 的 Sources 选项卡中看到它们。

我的 file.js 的内容完全是从 jsfiddle 复制粘贴的:

$('body').on('click','a',function(e){
    e.preventDefault();
    createMyButton();
});

createMyButton = function(data) {    
    $('a').after('<div id="my-button">test</div>');        
};

$('body').on('click','#my-button',function (e) {
      alert("yeahhhh!!! but this doesn't work for me :(");
});

【问题讨论】:

  • 你在哪里点击事件处理程序?
  • 可以粘贴file.js的内容吗?
  • 假设您刚刚从小提琴中复制+粘贴,您可能错过了 document.ready 处理程序。虽然我不知道您希望我们如何解决我们看不到的代码问题...
  • 可能是两件事。 1、你的JS文件有问题。 2、尝试将&lt;script src="file"&gt;粘贴到&lt;body&gt;中链接开头的正上方。还要将type="text/javascript" 添加到您的script includes
  • 我已经粘贴了文件内容

标签: javascript jquery onclick


【解决方案1】:

由于您的代码位于 head 标记中,因此您需要使用 DOM 就绪包装器来确保您的代码在 DOM 呈现元素后执行。

jsfiddle 没有它,因为 fiddle 已经设置为在加载时运行代码。

$(function(){
    $('body').on('click','a',function(e){
        e.preventDefault();
        createMyButton();
    });

    createMyButton = function(data) {    
        $('a').after('<div id="my-button">test</div>');        
    };

    $('body').on('click','#my-button',function (e) {
         alert("yeahhhh!!! but this doesn't work for me :(");
    });
});

【讨论】:

    【解决方案2】:

    您的代码与 sn-p 一起使用。更好地与 document.ready 一起使用。在 document.ready 之后发布您的 js。并更改选择器 document 而不是 body

    $(document).ready(function() {
    
      $(document).on('click', 'a', function(e) {
        e.preventDefault();
        createMyButton();
      });
    
      createMyButton = function(data) {
        $('a').after('<div id="my-button">test</div>');
      };
    
      $(document).on('click', '#my-button', function(e) {
        alert("yeahhhh!!! but this doesn't work for me :(");
      });
    })
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <a href="#">asl;kdfjl</a>
    <div id="my-button">sdgdf</div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-14
      • 2016-05-13
      • 2019-02-11
      • 2018-06-15
      • 2017-08-22
      • 2012-11-07
      • 2018-03-06
      相关资源
      最近更新 更多