【问题标题】:Load External HTML and Add Event Handler for Element Declared in the HTML加载外部 HTML 并为 HTML 中声明的元素添加事件处理程序
【发布时间】:2013-12-05 06:18:32
【问题描述】:

在加载主 HTML 后,我有一个要加载的外部 HTML。

<!--external.html-->
<form id="externalForm">
    <div id="button">Button</div>
</form>

如何为“按钮”添加事件处理程序?

在主 HTML 中尝试了以下代码,

<!--main.html-->
<body>
<div id="extForm"></div><!--to be loaded when document.ready-->

<script>
$(document).ready(function() {
    // Fill extForm with div's declared in external.html
    $("#extForm").load("external.html");
}
// button.ready will be triggered after loading external.html
$("#button").ready(handlerCreator());

var handlerCreator = function () {
   return function() {
       alert("Working"); // since button is ready
       $("#button").on("click", function() {
           alert("Not working"); // why?
       });
   };
}

</script>

【问题讨论】:

  • 这里的括号要去掉:$("#button").ready(handlerCreator);
  • @Igle 括号 != 括号

标签: jquery events event-handling


【解决方案1】:

按钮没有准备好的处理程序...您需要使用事件委托

使用事件委托为#button注册处理程序

$(document).ready(function () {
    $("#extForm").load("external.html");
})
$("#extForm").on('click', '#button', function () {
    alert('button clicked')
});

或者在外部文件加载到dom后注册handler

$(document).ready(function () {
    $("#extForm").load("external.html", function () {
        $("#button").click(function () {
            alert('button clicked')
        });
    });
})

【讨论】:

  • 但是为什么会弹出第一个警报“Working”呢?
  • @JeffreyGoines 即使您将准备好的处理程序注册到button,它也与将其添加到文档中相同,因此当加载文档时,将执行handlerCreator 返回的方法
猜你喜欢
  • 1970-01-01
  • 2011-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-15
  • 1970-01-01
相关资源
最近更新 更多