2011-09-13 46 views
0

我怎样才能找到链接的片段与URL的片段匹配,然后突出显示链接的父级?使用jquery将链接的片段与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的容器元素应该被突出显示。

回答

3

优雅最短的解决方案

Live Demo

fragment = '#/story/article-3/'; 
$('.item a[href$="' + fragment + '"]').parent().css({background:'red'}); 

另一个不那么优雅的选择,但为什么按照预期的代码是不工作的一个例子。

Live Demo 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'}); 
     } 
    } 
); 
+0

谢谢Loktar! – laukok

1

只是filter了出不符合我们的片段和申请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'}); 
+0

好,但是你应该使用'parent()'而不是'父母'('div')',这样它只选择锚的父亲,而不是锚的DOM分支中的所有div。 –

+0

@Laurent OP在他的代码示例中使用了'parents()'。无论如何,我会改变它,因为它没有多大意义。谢谢。 –

+0

谢谢Sahil :-) – laukok

0

两个建议。

首先,你可能不需要所有的循环。看看Attribute Ends With Selector。这可能能够完成你的搜索。

一旦你的比赛,那么你应该能够做这样的事情:

$(this).parent().css('background-color', 'red'); 
+0

谢谢Axeva! – laukok