jQuery替换挂起chrome

Ell*_*sky 3 javascript jquery

为什么这个脚本会冻结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> 
Run Code Online (Sandbox Code Playgroud)

Bar*_*mar 7

因为执行替换的脚本位于正文中.当你调用.html(HTMLString)HTMLString包含a时<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> 
Run Code Online (Sandbox Code Playgroud)

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