0

I am trying to write a JS code to change color of the current link. For example, if page one address is www.abc.com/abc, and page 2 is www.abc.com/abc/product, then page one will turn red.Basically if page 2 is subpage of page1, then page 1 will turn red. Here is my idea:

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

Here are my codes below:

<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";
  }

}

Thank you for time!

4

2 回答 2

1

While on the surface of it, the answer is trivial, it appears that it is fairly common to do this kind of comparison wrong.

DO NOT DO:

// 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
于 2012-10-25T16:39:48.910 回答
0

It is really not possible to determine if a link actually IS pointing to a "parentpage" or a "subpage", but according to the examples given you can try to evaluate if the current page is a "subpage" of a link by their lengths and the current page prepends the link.

<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>

Please - i really dont want to be downvoted for this. It does what the question angles for, strange questions gives strange answers :)

于 2012-10-25T17:24:51.323 回答