gpt4 book ai didi

jquery - 非常有趣的 jQuery 加载行为,是错误还是解决方案?

转载 作者:行者123 更新时间:2023-12-01 06:16:30 26 4
gpt4 key购买 nike

我最近试图在一些脚本中找到一个错误,并且在使用 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警报
  • 来自 test2.htm 的 howdy 显示
  • 加载完成提醒

正如您所看到的,唯一的区别是 hello #2 警报的脚本标记为大写。显示 hello #1 警报的脚本永远不会被执行...

到目前为止,我已在 Firefox 3.55、IE 8.0.6001.18702 和 Chrome 3.0.195.33 中进行了测试,结果相似。

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

<小时/>

更新:正如下面 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>

最佳答案

实际上这似乎是 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, ""))

显然是不区分大小写的标志i缺少此正则表达式。因此每<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>

关于jquery - 非常有趣的 jQuery 加载行为,是错误还是解决方案?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1821047/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com