您好,这看起来很简单,但我不明白为什么第一个功能不起作用。我尝试了几种变体,但我的逻辑有问题。当我查看https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace时,我似乎已经正确完成了它,但它不会替换文本。在此先感谢您的帮助。
<!DOCTYPE html>
<html>
<body>
<p id="p1">Mr Red has a red house and a red car.</p>
<p id="p2">Mr Red has a red house and a red car.</p>
<button onclick="replace1()">Replace red with blue</button>
<button onclick="replace2()">Replace red with blue too</button>
<script>
function replace1()
{
var str = document.getElementById("p1").innerHTML;
str.replace(/red/, "blue");
document.getElementById("p1").innerHTML = str;
}
function replace2()
{
var str = document.getElementById("p1").innerHTML;
var rep = str.replace(/red/, "blue");
document.getElementById("p2").innerHTML = rep;
}
</script>
</body>
</html>
忽然笑
相关分类