gpt4 book ai didi

javascript - jQuery 替换挂起 chrome

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:31:38 28 4
gpt4 key购买 nike

为什么这个脚本会卡住 Chrome?另外,有没有更好的方法来做我想做的事情(用另一个词替换一个词的所有实例)?

<html>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
var replaced = $("body").html().replace('Foo','Bar');
$("body").html(replaced);
});
</script>
<p>Foo</p>
</body>
</html>

最佳答案

因为做替换的脚本在正文中。当您调用 .html(HTMLString)HTMLString包含 <script> , jQuery 执行脚本。因此,在替换主体之后,您将再次调用替换主体的代码,当它运行时,它会再次调用自身,依此类推。

每次进行替换时,您还会加载另一个 jQuery 副本,因为 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js">在体内。

一个解决方案是将所有脚本放在 <head> 中而不是 body 。另一种情况是,如果您只定位包含页面实际内容的容器 DIV。

<html>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
var replaced = $("#content").html().replace(/Foo/g,'Bar');
$("#content").html(replaced);
});
</script>
<div id="content">
<p>Foo</p>
</div>
</body>
</html>

此外,当您将字符串作为 .replace() 的第一个参数时, 它只替换第一个匹配项。如果要替换所有匹配项,则需要使用带有 g 的正则表达式修饰符。

关于javascript - jQuery 替换挂起 chrome,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36347139/

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