我最近试图在某些脚本中找到一个错误,并在使用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>
Run Code Online (Sandbox Code Playgroud)
文件#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>
Run Code Online (Sandbox Code Playgroud)
现在,当我运行Test1.htm时,我得到以下内容:
正如您所看到的,唯一的区别是脚本标记大写为hello#2警报.显示hello#1警报的脚本永远不会被激活...
到目前为止,我已经在Firefox 3.55,IE 8.0.6001.18702和Chrome 3.0.195.33中对此进行了测试,结果相似.
在过去,我想从加载的内容中提取javascript,类似于这个SO问题.所以我的问题是,这是一个错误还是一个解决方案?
更新:正如下面的Jitter所述,如果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>
Run Code Online (Sandbox Code Playgroud)
实际上这似乎是jQuery中的一个错误.你应该发一个错误票.很好找到顺便说一句.
在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, ""))
Run Code Online (Sandbox Code Playgroud)
很明显i,这个正则表达式上不区分大小写的标志丢失了.因此,每一个<script>...</script>标签,它是不是所有的小写一样<SCRIPT>,<Script>,<scriPt>,...是不是的jQuery去除预期.
所以第3272行应该是这样的
.append(res.responseText.replace(/<script(.|\s)*?\/script>/gi, ""))
Run Code Online (Sandbox Code Playgroud)
此外,只有您在加载网址中使用选择器才会触发此错误test2.htm #content.如果你把它留下并使用
$('#test').load('test2.htm',function(){....});
Run Code Online (Sandbox Code Playgroud)
和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>
Run Code Online (Sandbox Code Playgroud)