如何加载Jquery的响应(HTML页面脚本标签)到DOM [英] how to load the Jquery response(HTML page with script tags) into the DOM

查看:289
本文介绍了如何加载Jquery的响应(HTML页面脚本标签)到DOM的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

test1.html文件:

test1.html file:

<html>
<head>
<script src="jquery-1.7.2.js">
</script>
<script>

function loadfn(){

$.get('test.html',function(data){

alert($(data).text());
//$('body div#returnData').html(data);
$.each(data, function(i, node) { 
    alert(i);
   if (node.tagName == "SCRIPT") {
       eval(node.innerHTML); 

   } else {
       $(node).appendTo($('#returnData')); 
   }

});

});
test1();
test2();
}
</script>
</head>
<body>
<div id="returnData" >
</div>
<input type="button" value="Click" onclick=loadfn()>
</body>
</html>

test.html的:

test.html :

<html>
<head>
<script src="/jquery-ui-timepicker-addon.js">
</script>
</head>
<script>
function test1(){
alert('test1 function');
}
</script>
<script>
function test2(){
alert('test2 function');
}
</script>
<body>
<div id="testdiv">
Text field : <input type="text" value="Test Value"/>
</div>
</body>
</html>

其实我有我要的页面的test.html加载到test1.html然后运行是否有在该网页的脚本功能的要求。

Actually i have the requirement that i have to load the test.html page into test1.html and then run the script functions that are there in that page.

以上code片段犯规足够的需求。请让我知道我在做什么错在code片段。

The Above code snippet doesnt suffice the requirement. Please let me know what i am doing wrong in the code snippet.

推荐答案

您不必加载到你的DOM。
对于脚本标记,你可以只是做..

You need not "load" it into your DOM. For script tags, you could just do..

eval("<script>alert('Hi!');</script>");

更新:

如果您导致包含的两个 HTML和脚本的节点,请执行下列操作。

If you result contains both HTML and SCRIPT nodes, do the following..

$.each(nodes, function(i, node) { //result might contain muliple HTML/Script nodes

   if (node.tagName == "SCRIPT") {
       eval(node.innerHTML); 
       //Appending to DOM also executes the script. So we do eval() instead, which does the equivalent.
   } else {
       $(node).appendTo($('#returnData')); //And append your HTML nodes to the desired target div
   }

});

这篇关于如何加载Jquery的响应(HTML页面脚本标签)到DOM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆