How can I find the match in a link's fragment with the url's fragment and then highlight the link's parent开发者_运维百科?
HTML,
<div class="item">
<a href="http://example.come/#/story/article-1/">Link 1</a>
</div>
<div class="item">
<a href="http://example.come/#/story/article-2/">Link 2</a>
</div>
<div class="item">
<a href="http://example.come/#/story/article-3/">Link 3</a>
</div>
<div class="item">
<a href="http://example.come/#/story/article-4/">Link 4</a>
</div>
jquery,
//var fragment = location.hash;
fragment = '#/story/article-3/';
string = $('.item').find('a').attr('href');
array_string = string.split('#');
last_item = array_string[array_string.length - 1];
if(fragment == '#'+last_item)
{
alert('match!');
// this is my theory... but I don't know how to get the object that matches the fragment.
match_object.parents().css({background:'red'});
}
So, in this case, the Link 3's container element should be highlighted.
Elegant shortest solution
Live Demo
fragment = '#/story/article-3/';
$('.item a[href$="' + fragment + '"]').parent().css({background:'red'});
Another less elegant option but an example of why your code wasn't working as expected.
Live Demo 2
Without using .each
you will only get the href for the first link, so it can never match the other. So basically I just took your logic wrapped it with each, and modified your selector a bit to turn the div background red. I recommend option one however.
//var fragment = location.hash;
fragment = '#/story/article-3/';
$('.item').find('a').each(
function(){
array_string = $(this).attr('href').split('#');
last_item = array_string[array_string.length - 1];
if(fragment == '#'+last_item)
{
alert('match!');
$(this).css({background:'red'});
}
}
);
Just filter out the links that don't match our fragment and apply css.
DEMO
var fragment = '#/story/article-3/';
$('div.item').find('a').filter(function(i) {
return $(this).attr('href').indexOf(fragment) > -1
}).parent('div').css({background:'red'});
Two suggestions.
First, you may not need all that looping. Take a look at the Attribute Ends With Selector. That may be able to accomplish the search for you.
Once you have the match, then you should be able to do something like this:
$(this).parent().css('background-color', 'red');
精彩评论