Javascript HTML DOM href 屬性 | getElementById使用注意事項

語法:Javascript 可使用下方法更換HTML a連結標屬性

anchorObject.href=URL

實例:

<html>
<head>
<script type="text/javascript">
function changeLink()
{
document.getElementById('myAnchor').innerHTML="W3School";
document.getElementById('myAnchor').href="http://www.w3school.com.cn";
document.getElementById('myAnchor').target="_blank";
}
</script>
</head>

<body>
<a id="myAnchor" href="http://www.microsoft.com">Microsoft</a>
<input type="button" onclick="changeLink()" value="Change link">
</body>

</html>

使用document.getElementById時需要特別注意,您需HTML標籤的ID要先產生,再去執行document.getElementById,不然會出現如的TypeError: null is not an object (evaluating 'document.getElementById('myAnchor').href="http://www.w3school.com.cn"')的錯誤。 

 

 

使用下列方法先在HTML還沒產生前呼叫changeLink()就會出現錯誤。

 

<html>
<head>
<script type="text/javascript">
function changeLink()
{
document.getElementById('myAnchor').innerHTML="W3School";
document.getElementById('myAnchor').href="http://www.w3school.com.cn";
document.getElementById('myAnchor').target="_blank";
}
changeLink();
</script>
</head>

<body>
<a id="myAnchor" href="http://www.microsoft.com">Microsoft</a>
</body>
</html>

 

 

或是使Javascript在Html之後與onClick之後再執行,就不會出現getElementById錯誤訊息
 

 

 

<html>
<head>
</head>
<body>
<a id="myAnchor" href="http://www.microsoft.com">Microsoft</a>
<script type="text/javascript">
function changeLink()
{
document.getElementById('myAnchor').innerHTML="W3School";
document.getElementById('myAnchor').href="http://www.w3school.com.cn";
document.getElementById('myAnchor').target="_blank";
}
changeLink();
</script>
</body>
</html>

 

Posted in Javascript

Find the last offers by SkyBet at www.bettingy.com BettingY.com Bonuses