开发者

anchor and hash values issues

开发者 https://www.devze.com 2023-02-10 11:17 出处:网络
I have the following code: <ul class=\"questions\"> <li><a href=\"#test1\">test1</a></li>

I have the following code:

<ul class="questions">
<li><a href="#test1">test1</a></li>
<li><a href="#test2">test2</a></li>
<li><a href="#test3">test3</a></li>
</ul>


<div id="test1">test1 text</div>
<div id="test2">test2 text</div>
<div id="test3">test3 text</div>

i use this script to highlight the wanted id anchor in the same page :

<script type="text/javascript">

$(docume开发者_运维技巧nt).ready(function() {

    $(function() 
    {
        $('a').click(function(event) {

           $(location.hash).css("background-color","red");


        });
    });

});
</script>

the anchor movement works but the highlight for the selected id don't work unless i refresh the page after the page load from the first time and also the current highlight don't disperse when i click another link


$(function() {});

is a shortcut for

$(document).ready(function(){})

so, as Alexander said, you don't need both.

If the highlight does not work, you could try:

$(function() {
    $('a').click(function(event) {
       $($(this).attr("href")).css("background-color","red");
    });
});

since you can't rely on the location that change after the click event. There is jQuery plugins that allow to add events to "on hash change", that could be a solution for you if you use it a lot.

edit: It's normal that the current highlight doesnt disappear when you click another link.

$(function() {
    $(location.hash).addClass("red");
    $('a').click(function(event) {
       $(".red").removeClass("red")
       $($(this).attr("href")).addClass("red");
    });
});

.red { background: red; }


The issue is the anchor's href is applied after the onclick event of the anchor is handled. Hence during the click event handling the hash of the location is not changed yet.

You can instead rely on the href attribute to change the color:

e.g:

<script type="text/javascript">
                    $(function() 
                    {
                            $('a').click(function(event) {
                                var divID = $(this).attr("href");
                                $(divID).css("background-color","red");
                            });
                    });
    </script>


Change:

<script type="text/javascript">

$(document).ready(function() {

    $(function() 
    {
        $('a').click(function(event) {

           $(location.hash).css("background-color","red");


        });
    });

});
</script>

To:

<script type="text/javascript">


        $(function() 
        {
            $('a').click(function(event) {

               $(location.hash).css("background-color","red");


            });
        });

    </script>


// This is a shortcut...
$(function() {});

 // for this...
$(document).ready(function(){});


this the final code that works globally thank you all for your quick responded i Appreciate it :)

<html xml:lang="en" xmlns="http://www.w3.org/1999/xhtml"

lang="en">

<script src="jquery.js"></script>
<meta http-equiv="Content-type" content="text/html; charset=UTF-8">
<style type="text/css" media="screen">

.red { background: red; }

</style>
</head>
<body>
<ul id="con">
<li><a href="#test1">test1</a></li>
<li><a href="#test2">test2</a></li>
<li><a href="#test3">test3</a></li>
</ul>

<div id="test1">test1 text</div>
<div id="test2">test2 text</div>

<span id="test3" >
<div>
dvdvdvdvdvdvdvdvdvdv
</div> 
</span>



<script type="text/javascript">

$(document).ready(function() {});
{
$('#con a[href*=#]').click(
function(){var elemId='#'+$(this).attr('href').split('#')[1];highlight(elemId);});

function highlight(elemId)
{
$(".red").removeClass("red")
$(elemId).addClass("red");

}
if(document.location.hash){highlight(document.location.hash);}
}

</script>
</body>
</html>


There are a number of issues with your script:

<script type="text/javascript">
$(document).ready(function() {
  $(function() 
  {
    $('a').click(function(event) {
      $(location.hash).css("background-color","red");
    });
  });
});
</script>

I'll start from the top:

Make sure to enclose your script in CDATA tags to prevent XML encoding issues:

<script type="text/javascript">
/* <![CDATA[ */
...code...
/* ]]> */
</script>

$(document).ready(...); is the same as $(function(){}); which many others have noted. What most people fail to realize is that it's designed to alias jQuery to $ (or whatever other name you'd prefer) to prevent namespacing conflicts:

jQuery(function($){
  ...code...
});

When the document.ready event has fired, there is no instance where you tell the current hash value to be highlighted:

$(hash).css('background-color', 'red');

Ok, so I'm using a variable named hash because there's no guarantee that the hash is set or that it will begin with a '#' sign (I'm looking at you IE).

function normalizeHash()
{
  var hash = location.hash;
  if (hash.length)
  {
    if (hash[0] != '#')
    {
      hash = '#' + hash;
    }
  }
  else
  {
    hash = '';
  }
  return hash;
}

because you want to toggle the colors off when another hash is set, you should be using classes

CSS:

.activeHash
{
  background-color: red;
}

JS:

$(hash).addClass('activeHash');

You'll need to remember to remove the classes from elements during the click function:

$('.activeHash').removeClass('activeHash');
$(hash).addClass('activeHash');

@Cybernate caught an issue I missed: the hash wont have changed until after the click event, the simple solution is to get the href of the anchor element, although this assumes that the href isn't written with the path (a work-around would be to also listen for the hashchange event):

hash = $(this).attr('href');

So to put it all together:

<script type="text/javascript">
/* <![CDATA[ */

function normalizeHash()
{
  var hash = location.hash;
  if (hash.length)
  {
    if (hash[0] != '#')
    {
      hash = '#' + hash;
    }
  }
  else
  {
    hash = '';
  }
  return hash;
}

jQuery(function($){
  var hash = normalizeHash();

  $(hash).addClass('activeHash');

  $('a').click( function(e){
    hash = $(this).attr('href');
    $('.activeHash').removeClass('activeHash');
    $(hash).addClass('activeHash');
  } );
});

/* ]]> */
</script>

Disclaimer: I didn't test any of this code, let me know if I've made a tyop of speeling mistak.

0

精彩评论

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