使用内联javascript加载jquery

时间:2011-12-09 20:49:24

标签: javascript jquery

我正在使用jquery load来获取不同页面上的div并将其插入到我的页面中。 像这样的事情:

$('#mydiv').load("/Pages/grid2.aspx" + " #otherpagediv");

在另一页的div中,div中有javascript。 javascript没有出现,只有html内容。有没有办法在指定的div中获取所有内容?

4 个答案:

答案 0 :(得分:6)

这有效:

$.get( '/Pages/grid2.aspx', function ( data ) {
    $( '#mydiv' ).html( $( '<div></div>' ).html( data ).find( '#otherpagediv' ).clone() );
});

现场演示: http://jsfiddle.net/FRbnD/4/show/light/

要了解演示,请查看构成它的两个页面的源代码:
演示的源代码:http://jsfiddle.net/FRbnD/4/
“其他页面”的源代码:http://jsfiddle.net/MWkSj/1/

我们的想法是通过$.get请求检索其他网页,然后找到#otherpagediv克隆。然后,将克隆附加到#mydiv。如果将克隆插入DOM,并且该克隆包含SCRIPT元素,则将执行该脚本。

答案 1 :(得分:2)

来自documentation

  

注意:使用不带后缀选择器的URL调用.load()时   表达式,内容在脚本出现之前传递给.html()   除去。这将在丢弃之前执行脚本块。

     

但是,如果调用.load()并将选择器表达式附加到   URL,在更新DOM之前删除脚本,   这就是他们永远不会被执行的原因。

答案 2 :(得分:0)

JavaScript也应该出现回应。您必须确保/Pages/grid2.aspx应从服务器端发送所需的响应。您传递给load方法的网址也有一个空格。我认为你应该纠正这个并尝试一下。

$('#mydiv').load("/Pages/grid2.aspx" + "#otherpagediv");

答案 3 :(得分:0)

http://www.coursesweb.net/ajax/execute-javascript-code-ajax-response_t

您可能会发现此页面有用,我使用过该脚本,它使用了eval()

// this function create an Array that contains the JS code of every <script> 
// then apply the eval() to execute the code in every script collected
 function parseScript(strcode) {
 var scripts = new Array();         // Array which will store the script's code

// Strip out tags
 while(strcode.indexOf("<script") > -1 || strcode.indexOf("</script") > -1) {
 var s = strcode.indexOf("<script");
 var s_e = strcode.indexOf(">", s);
 var e = strcode.indexOf("</script", s);
 var e_e = strcode.indexOf(">", e);

 // Add to scripts array
 scripts.push(strcode.substring(s_e+1, e));
 // Strip from strcode
 strcode = strcode.substring(0, s) + strcode.substring(e_e+1);
}

// Loop through every script collected and eval it
for(var i=0; i<scripts.length; i++) {
 try {
   eval(scripts[i]);
 }
  catch(ex) {
    // do what you want here when a script fails
  }
 }
}