如何在链接的片段中找到与url片段的匹配,然后突出显示链接的父片段?
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'});
}因此,在这种情况下,应该突出显示链接3的容器元素。
发布于 2011-09-13 13:47:53
雅致最短解
现场演示
fragment = '#/story/article-3/';
$('.item a[href$="' + fragment + '"]').parent().css({background:'red'});另一个不那么优雅的选项,但这是为什么您的代码不能像预期的那样工作的例子。
现场演示2
如果不使用.each,您将只能获得第一个链接的href,因此它永远无法与另一个链接相匹配。基本上,我只是把你的逻辑和每一个包在一起,修改了你的选择器,使div背景变红。不过,我建议选择一种。
//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'});
}
}
);发布于 2011-09-13 13:50:57
只需过滤器出与我们的片段不匹配的链接并应用css即可。
演示
var fragment = '#/story/article-3/';
$('div.item').find('a').filter(function(i) {
return $(this).attr('href').indexOf(fragment) > -1
}).parent('div').css({background:'red'});发布于 2011-09-13 13:53:11
有两点建议。
首先,你可能不需要所有的循环。看一看属性以选择器结尾。。也许能完成对你的搜寻。
一旦你有了比赛,你就应该能够做这样的事情:
$(this).parent().css('background-color', 'red');https://stackoverflow.com/questions/7402851
复制相似问题