2012-11-16 94 views
1

我试图加载从initial.html不同的HTML页面与另一页:负载与DOM改变

$("#hidden_demo_div").load("modules/another.html", function (data) { 
    var value = $(data).filter("#demo_div"); 
    var html = value.html(); // THERE IS NO <strong>Hello</strong> here!!! 
} 

这里从another.html

<html> 
    ......................... 
    <head> 
    <script type="text/javascript"> 
     $(document).ready(function() { 
      anotherMethodInvocation(); 
     }); 
    </script> 
    </head> 

    <div id="demo_div"></div> 
</html> 

下一个片段在JS为another.html我有:

function anotherMethodInvocation() {  
    $("#demo_div").append("<strong>Hello</strong>"); 
} 

所以问题是为什么我得到(在我的负载回调函数)只是静态的HTML,但没有改变?

UPDATE 1:

一) “#hidden_​​demo_div” 位于initial.html(HTML其中具有.load JS代码链接)。 这个元素是在BODY声明:

B)如果我把在BODY (一个HTML文件,它甚至不工作)

<div id="hidden_demo_div"></div> 

和 (到另一个HTML文件)

<div id="demo_div"></div> 

在身体。

+0

你没有头部后** ** 标签。 – Bruno

+0

你的结构看起来如何?我的意思是你的文件和这个方法在哪里运行? –

+0

请提供一些关于具有anotherMethodInvocation()的JS的更多信息。它是否在索引html或another.html中链接? – roncsak

回答

0

意识到当加载远程页面时,主页面已经发生了事件,这一点很重要。这意味着在远程页面中包装在$(document).ready(function() {}中的代码将立即触发。

如果远程文件中的代码位于HTML之前,则表示它不会找到该HTML,因为它在代码触发时不存在。

试试这个结构在远程页面:

<div id="demo_div"></div> 
<!-- "demo_div" now exists , can run code on it --> 
<script type="text/javascript">    
     anotherMethodInvocation(); 

</script> 
+0

'$(document).ready'等同于设置一个短暂超时,如果文档在调用时已经准备就绪,它将不会同步运行。请参阅https://github.com/jquery/jquery/blob/master/src/core.js#L845 – Esailija

+0

@Esailija不是当它在ajax加载的页面中使用时...''已准备好''已经发生 – charlietfl

+0

没有..脚本可以放在头部或身体中。正如我已经表明的,你需要将代码放在html后面的代码中。 – charlietfl