4 回答
TA贡献1829条经验 获得超9个赞
首先你的结束语有一个错字<script>
,漏掉了/
,应该是</script>
。然后你的脚本在 DOM 完全加载之前运行。您可以将脚本放在body标记的底部,也可以使用事件包装代码DOMContentLoaded
:
<script>
window.addEventListener('DOMContentLoaded', (event) => {
document.getElementById("upgrade").onclick = function () {
var el = document.getElementById("buylink");
el.href = "fancy_tickets.html";
console.log(el.getAttribute('href'));// log the new href value
};
});
</script>
<a id="buylink" href="ticket.html">Buy Tickets</a><br>
<button id="upgrade">Upgrade</button>
TA贡献1864条经验 获得超6个赞
你的代码运行良好。您忘记指定标签id="upgrade"的属性button。
document.getElementById("upgrade").onclick = function () {
document.getElementById("buylink").href = "fancy_tickets.html";
};
<a id="buylink" href="tickets.html">Buy Tickets</a><br>
<button id="upgrade">Upgrade</button>
TA贡献1893条经验 获得超10个赞
您应该使用setAttribute(atr, value);
类似的方法document.getElementById("buylink").setAttribute("href", "fancy_tickets.html");
。另外我建议您使用 addEventListener 来监听 onClick 等事件
const upgradeBtn = document.getElementById("upgrade");
const buyLink = document.getElementById("buylink");
upgradeBtn.addEventListener('click', () => {
buyLink.setAttribute("href", "fancy_tickets.html");
});
TA贡献1801条经验 获得超15个赞
function switch1()
{ document.getElementById("buylink").href = "fancy_tickets.html";
}
<html>
<body>
<a target=_blank id="buylink" href="tickets.html">Buy Tickets</a><br>
<button id="upgrade" onclick="javascript:switch1();">Upgrade</button>
</body>
</html>
添加回答
举报