为什么此脚本会冻结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>
正文中,而不是放在正文中。另一个可能是,如果您只定位了包含页面实际内容的容器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
修饰符的正则表达式。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句