包含的html中的类无法访问父文件html中的函数

class in the included html not able to access function in parent file html

本文关键字:html 文件 函数 访问 包含      更新时间:2024-01-09

我有一个包含以下内容的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"似乎不起作用。有没有办法让它也适用于包含的子页面?

附言-我试图使用"直播",但它抛出了一个错误

"未捕获类型错误:对象[Object Object]没有方法'live'"

我正在寻找一个除了"生活"之外的解决方案。谢谢

live抛出no method错误,因为它在1.9版本中已从jQuery中删除。它已被带有委托选择器的on取代。

您的问题是,您试图在内容加载完成之前将事件附加到.alertClass。尝试将事件挂钩放置在load:的回调中

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

或者,正如我所提到的,您可以将on与代理选择器一起使用:

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