开发者

javascript syntax problem

I have this in the head of my document:

<script type="text/javascript">

            var myString= location.href;
            var mySplit = myString.split("#开发者_JAVA技巧");
            var x = mySplit[1];

            if (x == 'page1_div1') {
                document.getElementById('div1').className = 'theNewClass';
            }
</script>

What is my error? Thanks, Linda


If you have that code in the head of your document as you say, the problem is that document.getElementById is not able to find your "div1" element, because when it is executed, the body of your document hasn't been evaluated, try to use the window.onload event:

window.onload = function () {
  var x = location.hash.substring(1);

  if (x == 'page1_div1') {
    document.getElementById('div1').className = 'theNewClass';
  }
};

Note that I also simplified your code a little bit, you wanted to extract the hash part of the current url.


You can get the hash more easily through location.hash and since you will likely have several divs, it's easier to switch on them. Example:

<script type="text/javascript">
  var myHash = location.hash || 'NO-HASH';

  switch (myHash) {
    case 'NO-HASH':
      // Original page - no hash.
      document.getElementById('div1').className = 'theOldClass';
      document.getElementById('div2').className = 'theOldClass';
      break;
    case '#page1_div1':
      document.getElementById('div1').className = 'theNewClass';
      document.getElementById('div2').className = 'theOldClass';
      break;
    case '#page1_div2':
      document.getElementById('div1').className = 'theOldClass';
      document.getElementById('div2').className = 'theNewClass';
      break;
  }
</script>

However, if this is related to your history tracking question, you'll want to run this code in a polling timer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜