2012-09-08 36 views
1

即时通讯使用jQuery的load()方法发送另一个html到我的网页。 正在加载的html包含Javascript生成的HTML。使用此功能加载HTML在ajax发送html + JS

林:

$(document).ready(function(){ 
    $("img#links").click(function(){ 
     $("div#content").load("links.html"); 
    }); 
    }); 

的links.html包含:

<h1 id="content">Links</h1> 
<br> 
<script>add_link("http://google.com");</script> 

的add_link函数生成我的表:

var add_link = function(link) { 
    document.write("<table border=\"0\" width=\"100%\" height=\"50\" id=\"link\">"); 
    document.write("<tr>"); 
    document.write("<td width=\"50\"><img src=\"img/star.png\" /></td>"); 
    document.write("<td><a href=\"" + link + "\"><div class=\"link\">" + link + "</div></a></td></tr></table>"); 
} 

然而,当被调用而不是将js生成的代码写入网页时,它会被写入空白页co仅获取由JS生成的表。

+1

考虑使用[javascript模板](http://stackoverflow.com/questions/7180582/templates-in-js)。 – moonwave99

回答

1

当您在页面加载完成后致电document.write() —绝对是这里的情况—浏览器将会清除原始页面。换句话说,浏览器在页面完成后解释一个呼叫是一个隐含的请求,用空白页面“重新开始”。

而不是使用document.write(),那么您可以使用DOM API将新内容附加到页面上。

+0

另外,如果你不能改变使用'document.write'的代码,那么你可能想通过覆盖[document.write'方法本身]来避开这个问题(https://gist.github.com/ 995079)。 –