2010-06-22 56 views
1

我不明白为什么这不起作用。它更改为第一个链接,不会继续。我也需要它来循环,所以当你点击它总是通过链接我有一个PHP变量,这是最后一个#panelNum。JavaScript onclick变化href

<html> 
<head> 
<script language="JavaScript"><!-- 
function findLinkByHref(href) { 
    for (var i=0; i<document.links.length; i++) { 
    if (document.links[i].href == href) return i; 
    } 
    return -1; 
} 

function changeLinkHref(id,newHref,oldHref) { 
    if (document.links.length > 0) { 
    if (document.getElementById) { 
     document.getElementById(id).href = newHref; 
    } 
    else if (document.all) { 
     document.all[id].href = newHref; 
    } 
    else { 
     var index = findLinkByHref(oldHref); 
     if (index > -1) 
     document.links[index].href = newHref; 
    } 
    } 
} 
//--></script> 
</head> 
<body> 
<a id="myLink" href="#panel3" value="Change href" onClick="changeLinkHref('myLink','#panel4','#panel5','#panel5','#panel6')">somewhere</a> 
</body> 
</html> 

回答

1
function findLinkByHref(href) { 
    for (var i=0; i<document.links.length; i++) { 
    if (document.links[i].href == href) return i; 
    } 
} 

如果您在返回如果它仍返回 - 因此停止你的函数的执行。

这是唯一的for循环,因此唯一的地方是你遍历所有的链接。这听起来像你想在changeLinkHref函数中这样做,就像..

else if (document.all) { 
     document.all[id].href = newHref; 
    } 
    else { 
     var index = findLinkByHref(oldHref); 
     for (var i=0; i<document.links.length; i++) { 
     // change all links? 
0

你可以做这样的事情。

JS

function A() { 
document.getElementById("B").href="http://empireminecraft.com/"; 
} 

HTML

<button type="button" onClick="A()">Yo!</button> 
<a href="https://duckduckgo.com/?q=web+validator" id="B">Yo!</a> 

我只是使用的URL,我不得不打开。 由于某种原因,当我尝试它时,我只能让它在IE中运行