日期:2014-05-16  浏览次数:20391 次

getElementsByTagName("name")[n]用这种方式正确吗?
HTML code
<title>无标题文档</title>
<script type="text/ecmascript">
function changeLink(){
    var firstLink = document.getElementsByTagName("a")[0];
    if(firstLink.href == "search.html"){
        firstLink.href = "http://www.google.com";
    }
}
window.onload = changeLink;
</script>
</head>

<body>
<a href="search.html">导航</a>
<a href="#">首页</a>
</body>


HTML code

<title>无标题文档</title>
<script type="text/ecmascript">
function changeLink(){
    var firstLink = document.getElementsByTagName("a");
    for(var i=0;i<firstLink.length;i++){
        if(firstLink[i].href == "search.html"){
            firstLink[i].href = "http://www.google.com";
        }
    }
}
window.onload = changeLink;
</script>
</head>

<body>
<a href="search.html">导航</a>
<a href="#">首页</a>
</body>



写成下面这种样子也不会把链接地址换了

------解决方案--------------------
HTML code

<title>无标题文档</title>
<script type="text/ecmascript">
function changeLink(){
    var firstLink = document.getElementsByTagName("a")[0];

    if(firstLink.getAttribute('href') == "search.html"){
        firstLink.setAttribute('href', "http://www.google.com");
    }
}
window.onload = changeLink;
</script>
</head>

<body>
<a href="search.html">导航</a>
<a href="#">首页</a>
</body>