如何使用<脚本>更改 href

How to change href using <script>?

本文关键字:更改 href 脚本 何使用      更新时间:2023-09-26

我试图在脚本中 400 毫秒后更改 id 的 href,但是当我转到页面时,400 年后链接仍然相同。

<script>
    setTimeout(function(){document.getElementById(3).href=
    '/cgi-bin/mancalaV9eam.cgi/retro/2/3/1/4/4/4/0/5/5/1/5/4/4/4/4/4/0';}, 400);
</script>
元素

id是一个字符串,因此您需要将 id 包装在引号中以getElementById

 setTimeout(function(){document.getElementById("3").href=
    '/cgi-bin/mancalaV9eam.cgi/retro/2/3/1/4/4/4/0/5/5/1/5/4/4/4/4/4/0';}, 400);
<a href="http://google.com" id="3">Does this still go to google?</a>

正如评论中指出的那样,id通常不应该以数字开头,但它确实有效。

Document.getElamentById 需要一个区分大小写的字符串,表示所查找元素的唯一 ID。

所以你需要给它传递一个字符串,但不清楚脚本中的 3 到底指的是什么。