我正在尝试动态更新多个位置的文本。不过我知道下面的代码不起作用,因为同一个 ID 被多次使用。有什么想法吗?
<html>
Favorite things to eat<p id="fruit">Text will appear</p>
Things that grow on trees<p id="fruit">Text will appear</p>
Dinner<p id="fish">Text will appear</p>
Creature in the ocean<p id="fish">Text will appear</p>
</html>
Javascript:
<script>
document.getElementById("fruit").innerHTML="Oranges";
document.getElementById("fish").innerHTML="Shark";
</script>
最佳答案
您不能多次使用该 ID。
但是,您可以为元素分配一个类,并使用 jquery 获取该类的每个元素。
<p class="fruit">text will appear</p>
脚本。
<script type="text/javascript">
$(".fruit").html("Oranges");
</script>
关于javascript - 如何在多个位置使用innerHTML?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18920103/