2014-12-07 79 views
1

我想將一個錨標籤放置在一個文檔元素中,該元素具有附加的jQuery .slideToggle函數。jQuery .slideToggle用法

這是HTML:

<section id="recent_articles"> 

<article> 

<img src="images/image1.jpg"> 
<h1>Insert title here</h1> 
<p>Insert text here followed by an anchor tag<a href=#>Read More</a></p> 

</article> 

</section> 

The jQuery looks like this: 

$("#recent_articles > article").click(function(e) { 

     $(this).children("p").slideToggle(1000); 
     $(this).toggleClass("open"); 

    }); 

據我瞭解,jQuery是「激活」只要單擊文章元素(包括圖像元件)和段落滑動向下和向上的指示。

但這意味着錨元素無法訪問,因爲它響應jQuery而不是href屬性。

使用jQuery,我將如何訪問anchor元素,以便它使用默認鏈接行爲進行響應,而不是使用.slideToggle函數。

我非常非常新的使用jQuery,所以任何意見將不勝感激。

+0

所以你基本上要放錨裏面的鏈接,對不對?它應該導航到同一頁面內的某些內容,但您希望它阻止觸發動畫,對不對? – 2014-12-07 23:36:07

+0

正確,但鏈接錨點應轉到新頁面。目前,單擊段落內的鏈接只會觸發.slideToggle函數。 – 2014-12-07 23:44:31

+0

奇怪的是,它應該在任何情況下導航......除非你在某處使用'return false'或'event.preventDefalt()'... – 2014-12-07 23:46:25

回答

1

點擊您可以在觀看event.target元素標籤名(誰被稱爲該事件的一個),
如果它不是一個錨"A"比做的事

$("#recent_articles > article").click(function(ev) { 
    if(ev.target.tagName!=="A"){ 
    $(this).children("p").slideToggle(1000); 
    $(this).toggleClass("open"); 
    } 
}); 

否則你可以做它就像你已經做的只是添加綁定到a元素的另一個功能,將阻止點擊事件傳播冒泡)到article

$("#recent_articles > article").click(function(e) { 
    $(this).children("p").slideToggle(1000); 
    $(this).toggleClass("open"); 
}).find('a').click(function(e){ // find `a` inside `article` and on click... 
    e.stopPropagation();   // don't propagate the event up to `article` 
}); 

P.S:你的函數可以還短有點像:

$("#recent_articles > article").click(function(e) { 
    $(this).toggleClass("open").children("p").slideToggle(1000); 
}).find('a').click(function(e){ 
    e.stopPropagation(); 
});