2013-07-12 39 views
14

下面的代码有效。如果有更好的方法,请让我知道。 如果我使用脚本内容,它出现在我通过ajax加载test.html的主页中的test.html中。该脚本不起作用。jquery事件不能处理ajax加载的内容

<html> 
    <head> 
     <script src='jquerylocation' type='text/javascript'></script> 
    </head> 
    <body> 
     <div id='ajaxload'></div> 
     <button class='test'>load content via ajax</button> 
    </body> 


    <script> 
     $(function(){ 
      $('.test').on('click',function(){ 
        $('#ajaxload').load('test.html'); 
      });    
     }); 
    </script> 
</html> 

的test.html:

<h1 class='heading'>Page via AJAX</h1> 

    <script> 
     $(function(){ 
      $('.heading').on('click',function(){ 
       $(this).css('color','red'); 
      });       
     }); 
    </script> 

我们要通过AJAX动态加载的内容一起加载脚本工作,因为你require.But缺点我觉得是每次我们发送Ajax请求的负载脚本所有的时间与内容一起。但是我发现只有这个解决方案。如果有人知道更好的解决方案,请回复

例如,如果以这种方式更改代码,它将无法正常工作。

<html> 
    <head> 
     <script src='jquerylocation' type='text/javascript'></script> 
    </head> 
    <body> 
     <div id='ajaxload'></div> 
     <button class='test'>load content via ajax</button> 
    </body> 


    <script> 
     $(function(){ 
      $('.test').on('click',function(){ 
        $('#ajaxload').load('test.html'); 
      }); 

      $('.heading').on('click',function(){ 
       $(this).css('color','red'); 
      });         
     }); 
    </script> 
</html> 

的test.html:

<h1 class='heading'>Page via AJAX</h1> 
+1

这是因为你在的document.ready功能,这将不是一个AJAX调用完成后调用加以包装。您可以尝试在load()调用中的成功回调函数中添加事件处理程序,或者使用主页的脚本部分 – Derek

+0

上全局定义的延迟事件,请再次检查我的问题,然后对其进行编辑。并请请一些代码 –

+0

回复也确保你定义脚本标签瓦特/合适的属性,即'<脚本类型=“文/ JavaScript的”>' – Derek

回答

41

这是因为你具有约束力的文件准备的事件。你必须使用一个委托才能工作。像on。这是因为.header在加载时不在页面上。所以没有附加任何事件。

您的代码应沿着一些这样的台词:

$('body').on('click','.heading',function(){ 
    $(this).css('color','red'); 
}); 

它不必为身体,但是文件准备好,这是父后不加载的元件。标题

+0

哦酷让我检查..你要我在代表风格 –

+1

谢谢学到了一课:) –

+2

这就是这个网站是所有关于,很高兴你喜欢的答案! :) –

0

一种选择是在初始化成功加载脚本:

$('.test').on('click',function(){ 
    $('#ajaxload').load('test.html',function(){ 
     $('body').on('click', '.heading', function(){ 
      $(this).css('color','red'); 
     }); 
    }); 
});