0

現在のリンクの色を変更するJSコードを書き込もうとしています。たとえば、ページ1のアドレスがwww.abc.com/abcで、ページ2がwww.abc.com/abc/productの場合、ページ1は赤になります。基本的に、ページ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";
  }

}

お時間をいただきありがとうございます!

4

2 に答える 2

1

表面的には答えは些細なことですが、この種の比較を間違って行うことはよくあることのようです。

するな:

// compare at most `haystack.length - needle.length' characters
// haystack is usually the longest string
haystack.indexOf(needle) == 0

行う:

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

リンクが実際に「親ページ」または「サブページ」を指しているかどうかを判断することは実際には不可能ですが、与えられた例によれば、現在のページがリンクの長さによってリンクの「サブページ」であるかどうかを評価することができます現在のページにはリンクが追加されます。

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

お願いします-私は本当にこれに反対票を投じたくありません. それは質問の角度を行います、奇妙な質問は奇妙な答えを与えます:)

于 2012-10-25T17:24:51.323 に答える