温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

jQuery.fn.load调用时给url加selector之后执行脚本的方法

发布时间:2020-07-09 11:23:59 来源:网络 阅读:962 作者:边城__ 栏目:web开发

调用jQuery.fn.load时是可以在url后面加选择器来指定加载的内容的。文档里这样描述:

默认使用 GET 方式 - 传递附加参数时自动转换为 POST 方式。jQuery 1.2 中,可以指定选择符,来筛选载入的 HTML 文档,DOM 中将仅插入筛选出的 HTML 代码。语法形如 "url #some > selector"。请查看示例。

  1. $("#links").load("/Main_Page #p-Getting-Started li"); 

不过有一个问题,如果指定了选择器,页面里的脚本就不会执行,查看了jQuery的代码之后发现,原来是有选择器的时候,将所有脚本过滤掉了

jQuery 1.8.3源码两个片段: 

  1. rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, // 逗号是因为这是一个语句的一部分 
  1. // See if a selector was specified 
  2. self.html( selector ?
  3.   
  4.     // Create a dummy div to hold the results 
  5.     jQuery("<div>") 
  6.  
  7.         // inject the contents of the document in, removing the scripts 
  8.         // to avoid any 'Permission Denied' errors in IE 
  9.         .append( responseText.replace( rscript, "" ) ) 
  10.  
  11.         // Locate the specified elements 
  12.         .find( selector ) : 
  13.  
  14.     // If not, just inject the full result 
  15.     responseText ); 

那么,如果想执行页面中的脚本,只需要找到页面内容中的脚本再执行一次就行了。在load的callback中,是可以取到整个页面内容的,所以只需要一句话就可以解决:

  1. $("#place_holder").load("Page.html #content"function(html) { 
  2.     // 加载html内容到页面上,里面的css和script都会执行 
  3.     // 加载之后即把当前的临时DIV删掉(没验证,如果有问题可以不remove) 
  4.     $("<div>").html(html).remove(); 
  5. }); 

不过既然jQuery要把脚本过滤掉就有它的道理……因为html里的css和script有可能会有一部分是不想调用的,怎么处理呢?用与jQuery过滤script的类似的办法,把所有script找出来,再选出需要执行的来执行。

于是,约定,在script中加入一个属性loadinvoke="true"的会在加载内容后执行,如定义这样的<script>:

  1. <script type="text/javascript"> 
  2.     console.log("这是不需要jQuery.fn.load时执行的脚本") 
  3. </script> 
  4.  
  5. <script type="text/javascript" loadinvoke="loadinvoke"> 
  6.     console.log("这是需要jQuery.fn.load时执行的脚本") 
  7. </script> 

给加载的脚本加点料:

  1. rscript = /<script\b[^>]*\b loadinvoke \b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi; 
  2.  
  3. $("#place_holder").load("Page.html #content"function(html) { 
  4.     // 找出符合条件的脚本 
  5.     var m = html.match(rscript); 
  6.     for (var i = 0; i < m.length; i++) { 
  7.         // 生成临时的div执行脚本 
  8.         $("<div>").html(m[i]).remove(); 
  9.     } 
  10. }); 

抛砖引玉

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI