代码之家  ›  专栏  ›  技术社区  ›  Mottie

非常有趣的jquery加载行为、bug或解决方案?

  •  1
  • Mottie  · 技术社区  · 15 年前

    我最近试图在一些脚本中找到一个bug,在用jquery加载页面时发现了这个非常有趣的行为。

    文件1:test1.htm

    <div id="test"></div>
    
    <script type="text/javascript">
    $(document).ready(function(){
     $('#test').load('test2.htm #content',function(){
      alert('done loading!');
     })
    })
    </script>
    

    文件2:test2.htm

    <div id="content">
    howdy
    
    <script type="text/javascript">
    $(document).ready(function(){
     alert('hello #1');
    })
    </script>
    <SCRIPT type="text/javascript">
    $(document).ready(function(){
     alert('hello #2');
    })
    </SCRIPT>
    
    </div>
    

    现在,当我运行test1.htm时,我得到以下信息:

    • 你好,2报警
    • howdy from test2.htm显示
    • 已完成加载警报

    正如您所看到的,唯一的区别是脚本标记是hello 2警报的大写。显示Hello 1警报的脚本永远无法执行…

    到目前为止,我已经在火狐3.55,即8.0.6001.18702和Chrome3.0.195.33中测试过了这个功能,并得到了类似的结果。

    在过去,我想从加载的内容中执行javascript,类似于 this SO question . 所以我的问题是,这是一个bug还是一个解决方案?


    更新:正如下面的抖动状态,如果test2.htm的脚本在我加载的内容之外,也会发生同样的事情。

    <div id="content">
    howdy from test2.htm
    </div>
    
    <script type="text/javascript">
    $(document).ready(function(){
     alert('hello #1');
    })
    </script>
    <SCRIPT type="text/javascript">
    $(document).ready(function(){
     alert('hello #2');
    })
    </SCRIPT>
    
    2 回复  |  直到 15 年前
        1
  •  9
  •   jitter    15 年前

    实际上,这似乎是jquery中的一个bug。你应该贴一张错误通知单。尼斯发现BTW.

    jQuery 1.3.2 我们有3270-3272号线

    // inject the contents of the document in, removing the scripts
    // to avoid any 'Permission Denied' errors in IE
    .append(res.responseText.replace(/<script(.|\s)*?\/script>/g, ""))
    

    显然是不区分大小写的标志 i 在这个regex上丢失了。因此,每一个 <script>...</script> 标签不是所有的小写形式 <SCRIPT> , <Script> , <scriPt> ,…未按预期被jquery删除。

    所以3272行应该是

    .append(res.responseText.replace(/<script(.|\s)*?\/script>/gi, ""))
    

    此外,此错误仅由在加载URL中使用选择器触发。 test2.htm #content . 如果你把那个放在外面用的话

    $('#test').load('test2.htm',function(){....});
    

    test2.htm 下面的内容看起来也会触发三个警报(无论您如何编写脚本标记)。所以这也是一个角落案例错误。

    howdy
    
    <SCRIPT type="text/javascript">
    $(document).ready(function(){
     alert('hello #1');
    });
    </SCRIPT>
    <script type="text/javascript">
    $(document).ready(function(){
     alert('hello #2');
    })
    </script>
    
        2
  •  2
  •   Community Ramakrishna.p    7 年前

    通过HTML注入脚本元素是很难可靠地跨浏览器完成的,因此 broken in various ways 在jQuery中。它可以解决一些已知的浏览器问题,但最终会使问题变得更糟。

    随着抖动的错误(+1)的修复,你会发现脚本根本没有被插入,以尽量避免这些问题。即使有了修复,这行代码也是可恶而脆弱的,试图用regex处理HTML,如果字符串 /script> 包含在脚本块中(非常有效)。并将失败 </script > .等等。

    帮你自己个忙然后离开 <script> 您打算动态加载的HTML内容。始终传递要与HTML分开执行的任何脚本内容。