简体   繁体   English

动态更改 HTML 属性

[英]Change HTML attributes dynamically

Can somebody explain where I'm making mistake, please..!有人可以解释我哪里出错了,请..!

Create a link that says “Buy Tickets” and has a href attribute of “tickets.html”.创建一个链接,上面写着“Buy Tickets”,并且具有“tickets.html”的 href 属性。

Create a button that says “Upgrade”.创建一个显示“升级”的按钮。

When the user clicks “Upgrade”, the “Buy Tickets” link url should change from “tickets.html” to “fancy_tickets.html”.当用户点击“升级”时,“买票”链接 url 应该从“tickets.html”变为“fancy_tickets.html”。

<script>
document.getElementById("upgrade").onclick = function () {
  document.getElementById("buylink").href = "fancy_tickets.html";
};
</script>

<html>
<body>
<a id="buylink" href="tickets.html">Buy Tickets</a><br>
  <button id ="upgrade">Upgrade</button>
</body>
</html>

First of all you have a typo in closing <script> , missing / , should be </script> .首先,您在关闭<script>有一个错字,缺少/ ,应该是</script> Then your script is running before the DOM is fully loaded.然后你的脚本在 DOM 完全加载之前运行。 You can either place the script at the bottom of the body tag or wrap your code with DOMContentLoaded event:您可以将脚本放在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>

Like it says in this question , you should use the setAttribute(atr, value);就像在这个问题中所说的那样,你应该使用setAttribute(atr, value); method, something like document.getElementById("buylink").setAttribute("href", "fancy_tickets.html");方法,类似于document.getElementById("buylink").setAttribute("href", "fancy_tickets.html"); . . Also i suggest you to use addEventListener to listen to events such as onClick另外我建议你使用 addEventListener 来监听 onClick 等事件

const upgradeBtn = document.getElementById("upgrade");
const buyLink = document.getElementById("buylink");

upgradeBtn.addEventListener('click', () => {
   buyLink.setAttribute("href", "fancy_tickets.html");
});

Your code works well.您的代码运行良好。 You forgot to specify the id="upgrade" attribute for the button tag.您忘记为button标记指定id="upgrade"属性。

 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>

 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM