0

如果您查看我的代码..单击父项会隐藏子项。我想要它做的是,能够href在父级之外创建一个,并将其作为触发子级隐藏功能的一个。我可以通过分配 ID 轻松实现这一点,但我想知道如何使用它来实现这一点,$(this)以便可以重复使用?

onClick $(this)链接 - 目标$(this)父 div - 隐藏$(this)子 div

<div class="trigger-collapse">   
     <h1>Anything here?</h1>
     <div class="content-collapse">
        <h4>Hello</h4>
        <p>We’re working really hard to not act like other wireless carriers. 
           At T‐Mobile you will always get fair and simple pricing, anytime upgrades, 
           a fast nationwide 4G network, no annual contracts, no overages and no 
           restrictions. Ever.
        </p>
     </div><!-- content collapse -->
</div> <!-- trigger collapse -->

到目前为止的 jQuery 脚本

$('.trigger-collapse').click(function() {
    $(this).children('div.content-collapse').toggle()
});
4

4 回答 4

0

听起来它会很快变得混乱。

一旦您发现可以轻松找到触发器和目标,我会给他们类(使其可重用)将其包装在类 div 中。额外的点把你的代码放在一个函数中。然后你可以使用自定义类。

如果这不起作用,您可以使用事件。

于 2013-10-27T19:52:21.347 回答
0

好吧,这取决于你想要它的布局方式。

如果<a href>标签在您的trigger-collapsediv 之前,那么您可以执行以下操作:

$('a').click(function() {
    $(this).next('.trigger-collapse').find('.content-collapse').toggle()
});

jsFiddle

或者,如果是之后,您可以.next()换掉.prev()

还有其他选择器,例如.siblings()which 也可以使用。

在元素上设置 ID 无疑是最简单的方法,如果你想拥有多个相关性,则设置类。这不应该真的使它的可重用性降低。但是,无论您想以哪种方式接近它,都有不止一个正确答案,真的。

于 2013-10-27T19:52:57.503 回答
0

html:

<div class="trigger-collapse">   
 <h1>Anything here?</h1>
 <div class="content-collapse" style="background-color:red; overflow:hidden;">

    <h4>Hello</h4>
    <p>We’re working really hard to not act like other wireless carriers. 
       At T‐Mobile you will always get fair and simple pricing, anytime upgrades, 
       a fast nationwide 4G network, no annual contracts, no overages and no 
       restrictions. Ever.
    </p>

 </div><!-- content collapse -->

jQuery:

$(".trigger-collapse").toggle(function(){
      $(".content-collapse").animate({height:0},600);
},function(){
      $(".content-collapse").animate({height:114},600);
});

http://jsfiddle.net/DRACg/2/

于 2013-10-27T19:58:06.477 回答
0

这个问题似乎有点令人困惑,但这可能是您想要的解决方案。我在内容折叠 div 之外放置了一个锚标记,但指向该 div 获取父节点/元素。

HTML:

<div class="trigger-collapse">   
    <h1>Anything here?</h1>
    <div class="content-collapse">
        <h4>Hello</h4>
        <p>We’re working really hard to not act like other wireless carriers. 
       At T‐Mobile you will always get fair and simple pricing, anytime upgrades, 
       a fast nationwide 4G network, no annual contracts, no overages and no 
       restrictions. Ever.
        </p>
   </div><!-- content collapse -->
   <a id ="outsideLink" href="#">Outside</a>
</div> 

jQuery :

$("#outsideLink").click(function(){
    //first got the anchor tag refence, then it's parent element and finally the desired div element
    $(this).parent().find("div.content-collapse").toggle();
});

演示

于 2013-10-27T19:59:06.670 回答