2014-12-07 71 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(); 
});