2012-09-29 205 views
0

雖然有很多好的資源用jQuery遍歷DOM,但我沒有任何運氣對我的例子。點擊jquery替代元素的鏈接

在我的網站www.smithgrey.co.uk我有一系列的縮略圖畫廊,在他們面前都有一個「欄目標題」div。

我想實現的是當您點擊'section-title'div時,點擊右邊縮略圖的第一個<a href>鏈接。

class="section-title"有多個實例 - 不幸的是,我無法添加任何ID或類,因爲它是動態生成的,並且被要求儘可能保持原樣。

的HTML看起來像這樣:

<body> 
    <div id="content-grid"> 
    <div class="section-title"> 
     <span class="section-title-type">Title of the first thumbnail gallery</span> 
    </div> 

    <div class="index-article"> 
     <a href="#" class="fancybox"> 
     <img src="thumbnail-1"> 
     </a> 
    </div> 

    <div class="section-title"> 
     <span class="section-title-type">Title of the second thumbnail gallery</span> 
    </div> 

    <div class="index-article"> 
     <a href="#" class="fancybox"> 
     <img src="thumbnail-2"> 
     </a> 
    </div> 

    <div class="index-article"> 
     <a href="#" class="fancybox"> 
     <img src="thumbnail-3"> 
     </a> 
    </div> 

    <div class="index-article"> 
     <a href="#" class="fancybox"> 
     <img src="thumbnail-4"> 
     </a> 
    </div> 
    </div> 
</body> 

這裏是我的jQuery,到目前爲止,但它並不能產生結果,我會想象,因爲它會點擊鏈接不管我點擊第一或第二<div class="section-title">

$('div.section-title').click(function(){ 
     $(this).parent().next($('div.index-article')).children('a.fancybox').click(); 
    }); 

解決方案:

隨着我所管理的其他評論者的幫助下找出如何使它工作如我所料:

$(document).ready(function() { 
    $('div.section-title').click(function(){ 
    $(this).next('.index-article').find('a.fancybox:first').click(); 
    }); 
}); 

回答

0

我會假設你已經安裝的正確的jQuery正確的事件/等。我就是這麼做的。請注意我已經在超鏈接中添加了一個單擊事件來模擬jsfiddle示例中的單擊。

http://jsfiddle.net/lucuma/s9mds/

$('div.section-title').click(function(e) { 
    $(this).next('div').find('a:eq(0)').click(); 
});​ 
+0

嘿,我給你的建議一去,但沒有運氣,但我開始用的.next(撥弄),我得到它的工作 - 所以謝謝你的幫助。 –

0

使用此

$(document).ready(function() { 
    $('div.section-title').click(function(){ 
    $(this).closest($('div.index-article').find('a.fancybox').click(); 
    }); 
}); 
+0

嘿感謝您的輸入,但它沒有給我任何結果,並在看着關於jQuery的文檔的closet()後,我可以看到它只在DOM中傳播,並且我假設我需要關閉 - 不確定是否會使任何差異。 –

+0

@SofusGraae但是在你的代碼中你正在向上 – StaticVariable

+0

嘿@jhonarymos對不起,如果我讓它看起來/聲音的方式。這個想法是,當你用class =「section-title」點擊div的第一個實例時,它會打開包含的鏈接。如果你另一方面按類class =「section-title-type」的第二個實例,那麼你將打開鏈接,這是包裝 - 這是否有任何意義(請記住,這不是我的日常工作,所以解釋我勉強可以包裹我的頭周圍是棘手的,但你的幫助是非常感謝:) –