我正在尝试编写一个JS代码来更改当前链接的颜色。例如,如果第一页地址是www.abc.com/abc,第2页是www.abc.com/abc/product,那么第一页将变为红色。基本上如果第2页是第1页的子页面,那么第1页将是变红。 这是我的想法:
compare char one by one in page1 and page2
if(currentpage.href!=one of a.href)
flag=false;
if(flag==true)
then turn red
else
then turn blue
以下是我的代码:
<div id="changeColor" class="horizontalcssmenu" style="padding-left:7px;">
<a href="linkeadress" >HOME</a>
<a href="linkaddress" >SHOP</a>
</div>
<script type="text/javascript">
var links = document.getElementById("changeColor");
var a = links.getElementsByTagName("a");
var thisLocationHref = window.location.href;
var counter=0;
for(var i=0;i<a.length;i++){
var flag="true";
var tempLink=a[i];
while(counter<=a[i].length){
if(thisLocationHref[counter]!=tempLink.href[counter])
{flag="false";}
counter++;
}
if(flag=="true")
{tempLink.style.color=red";
}
else
{
tempLink.style.color="blue";
}
}
感谢您的时间!
答案 0 :(得分:1)
虽然从表面上看,答案是微不足道的,看起来这种比较错误是相当普遍的。
不要这样做:
// compare at most `haystack.length - needle.length' characters
// haystack is usually the longest string
haystack.indexOf(needle) == 0
<强> DO:强>
// compare at most `needle.length' characters
// but never compare any characters, if the haystack is
// smaller then the needle
haystack.length >= needle.length &&
haystack.substr(0, needle.length) == needle
答案 1 :(得分:0)
确实无法确定链接是否实际指向“父页面”或“子页面”,但根据给出的示例,您可以尝试评估当前页面 是链接长度的“子页面”,当前页面是链接的前缀。
<div id="changeColor" class="horizontalcssmenu" style="padding-left:7px;">
<a href="http://localhost">HOME</a> <!-- www.abc.com/abc -->
<a href="http://localhost/products/">SHOP</a> <!-- www.abc.com/abc/prodct -->
</div>
<script type="text/javascript">
var links=document.getElementsByTagName('a');
for (var i=0;i<links.length;i++) {
//is length of the link less than current page?
if ((parseInt(links[i].href.length)<parseInt(window.location.href.length)) &&
//does the link prepending the current page?
(window.location.href.indexOf(links[i].href)>-1)) {
//probably this is a link to the "parentpage", eg "page 1"
links[i].style.color='#ff0000';
}
}
</script>
拜托 - 我真的不想为此付出代价。它做了问题的角度,奇怪的问题给出了奇怪的答案:)