我有一个包含以下内容的 mainfile.html

<html>
  <head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script>
    $(function(){
      $("#includedContent").load("d.html");

      $(".alertclass").click(function(){
         alert('some c load action');
      });

    });
    </script>
  </head>

  <body>
    <a class="alertclass" href="javascript:void(0);"> parent clicks heret </a>
    <br/>
     <div id="includedContent" ></div>

  </body>
</html>

我的“d.html”文件有内容
<div> <br/>
<a href="javascript:void(0);" class="alertclass">the child clicks here</a>
</div>

但是当我单击子页面中包含的内容中的链接时,“alertclass”类似乎不起作用。有没有办法让它也适用于包含的子页面?

附言- 我尝试使用“live”,但是它抛出了一个错误



我正在寻找除“现场”之外的解决方案。谢谢 !!

最佳答案

live 抛出 no method 错误,因为它在 1.9 版中从 jQuery 中删除。它已被 on 与委托(delegate)选择器一起使用所取代。

您的问题是因为您试图在内容加载完成之前将事件附加到 .alertClass。尝试将事件钩子(Hook)放在 load 的回调中:

$("#includedContent").load("d.html", function() {
    $(".alertclass").click(function(){
        alert('some c load action');
    });
});

或者,正如我提到的,您可以将 on 与委托(delegate)选择器一起使用:
$("#includedContent").load("d.html");
$(document).on('click', ".alertclass", function(){
    alert('some c load action');
});

10-07 18:55
查看更多