2011-09-13 8 views
0

URLのフラグメントを含むリンクのフラグメント内の一致を見つけて、リンクの親を強調表示するにはどうすればよいですか?URLのフラグメントとリンクのフラグメントをjqueryで照合しますか?

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背景を赤に変えました。しかし、私はオプション1をお勧めします。私たちのフラグメントと一致するとCSSを適用しないリンクアウト

//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

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')'の代わりに 'parent()'を使用して、アンカーのDOMブランチのすべてのdivではなく、アンカーの親しか選択しないようにしてください。 –

+0

@Laurent OPはコード例で 'parents()'を使用していました。私はそれがあまり意味がないので、とにかくそれを変更します。ありがとう。 –

+0

ありがとうございますSahil :-) – laukok

0

つの提案。

まず、すべてのループが必要なわけではありません。 Attribute Ends With Selectorをご覧ください。それはあなたのための検索を達成することができるかもしれません。

あなたは試合をしたら、あなたはこのような何かを行うことができるはず:

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

Axevaありがとう! – laukok

関連する問題