Determine which the link is hashtag
I'm a beginner with using jQuery and am experiencing a question.
I made a gallery and the gallery links are added to facilitate the hashtags user. For example, if 开发者_开发技巧you add a favorite link, to access the page will see the right image, because the hash tag is present in the link.
The gallery is almost working, actually I just wanted to add a class to make the selected image set.
$gallery = window.location.hash;
//If have no hashtag, adds the class on the first image
if( $gallery == '')
jQuery('.gallery-nav ul li').children('a').first().addClass('current');
else
{
jQuery('.gallery-nav ul li').each(function($i){
$link_hash = jQuery(this).find('a').attr('href');
if( $link_hash == $gallery)
{
alert ( $link_hash );
}
});
}
Until the first part, "If have no hashtag, adds the class on the first image" is working right, but then I do not know how. For example, if the the link is: http://example.net/gallery.php#3, I want to add the class on the third link.
In the above function, it shows the alert correctly. When it reaches the selected link it shows the alert. But I do not know how to add the class in the link.
Could anyone help me? Thanks.
You could just select that element directly using the attribute-ends-with-selector
(docs) to choose the element where the href
ends with the value of $gallery
. (I assume there are fewer than ten.)
As you can see, the $gallery
is concatenated into the selector string.
else {
jQuery('.gallery-nav ul li a[href$=' + $gallery + ']').addClass('current');
}
精彩评论