我有一个问题,如何在 div 标签中使用 javascript replace()?我是这样试过的:
<html>
<body>
<div id="ahoj">ahoj</div>
<script type="text/javascript">
document.write(document.getElementById("ahoj").replace("ahoj","hola"));
</script>
</body>
</html>
...但它不起作用...有什么想法吗?
最佳答案
document.getElementById("ahoj")
是一个 HTMLElement 对象。使用 document.getElementById("ahoj").innerHTML
document.write(document.getElementById("ahoj").replace(/ahoj/g,"hola"));
或者如果你不想要一个新元素:
document.getElementById("ahoj").innerHTML = document.getElementById("ahoj").innerHTML.replace(/ahoj/g,"hola");
替换字符串并将 innerHTML 设置为新字符串。 Example
关于javascript - 如何在div中使用replace?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7743085/