2012-03-07 31 views
0

很多關於此主題的可用內容,但是我沒有發現任何回答我的問題的內容......如果您發現這種多餘的內容,責備我。我非常努力地嘗試這個!jQuery IF窗口已經將它與一個數組進行比較,然後單擊一個匹配值

目標很簡單。我有一系列的div,其中一些包含錨點。我試圖將窗口的哈希值與div的錨點子元素的標題屬性進行比較,然後單擊匹配的元素的父元素。

我的函數下面記錄了正確的錨子數組,但我沒有看到點擊結果。我確定我錯過了一些東西。

感謝您的幫助。

<div class="box"><img src="#" /></div> 
<div class="box"><a href="#" title="blah"><img src="#" /></a></div> 
<div class="box"><img src="#" /></div> 

if(window.location.hash) { 
    var hash = window.location.hash.substring(1), 
     box = $('.box').children('a').each(function(){ 
        $(this).attr('title'); 
       }); 

    if (box.attr('title') == hash) { 
     $(this).parent().click(); 
    } 
} 

回答

1

從什麼樣子,你正在做那裏,$(this).attr('title')沒有做任何事情 - 它只是返回一個值,什麼都沒有用它做。

如果是我,我會做這樣的:

if(window.location.hash) { 
    var hash = window.location.hash.substring(1), 
     boxes = []; 

    $('.box').children('a').each(function(){ 
     if ($(this).attr('title') == hash) { 
      boxes.push(this); // OR: 
      $(this).parents("div.box").click(); 
     } 
    }); 

    // Or, you can iterate through your boxes array and perform more validation here. 
} 
相關問題