简体   繁体   English

jQuery onclick显示第一个父div

[英]jQuery onclick show first parent div

I have an issue with a show of a parent div at onclick. 我在onclick上显示父div时遇到问题。 As here: 如这里:

 $('#click').click(function() {
    $(this).parent().closest('div').slideToggle("fast");

});

http://jsfiddle.net/bk1hLoyb/

I need to show the .show div at the li click, and i need to hide the first when i click another. 我需要在li单击时显示.show div,并且在单击另一个时需要隐藏第一个。 Someone know's a method? 有人知道这是一种方法吗? Thanks so much 非常感谢

Id's should be unique on the page. ID在页面上应该是唯一的。

$('.click').click(function() {
        $('.show').hide();
        $(this).find('.show').slideToggle("fast");
    });

http://jsfiddle.net/bk1hLoyb/11/ http://jsfiddle.net/bk1hLoyb/11/

First Id's must be unique so change it for: 第一ID必须是唯一的,因此请将其更改为:

<li class="click">
        <a href="#">Bye</a>
        <div class="show">Hey</div>
</li>

and the code change it for: 并且代码将其更改为:

$('.click').click(function() {
        $(this).find('div').slideToggle("fast");
});

LIVE DEMO 现场演示

Some suggestions: 一些建议:

  • remove all duplicate IDs 删除所有重复的ID
  • if you must use a selector on the li elements, use a class 如果必须在li元素上使用选择器,请使用一个类
  • .show is a child of the li that's clicked, so there's no need to use .parent() or .closest() . .show是所单击的li的子级,因此无需使用.parent().closest()

Code: 码:

$('.click').click(function() {
    $('.show', this).slideToggle("fast");    
});

DEMO DEMO

BONUS 奖金

On your "li"s change the id to a class so you can reference multiple divs. 在“ li”上,将id更改为一个类,以便您可以引用多个div。

Then on the script looks like this: 然后在脚本上看起来像这样:

$('.click a').click(function() {
    var item = $(this);
    $(this).parent().siblings().find('.show').slideUp(400,function(){
        item.parent().find('.show').slideDown(400);
     });
});

See it working on your fiddle (sorry for updating without forking) 看到它正在您的小提琴上工作(很抱歉没有分叉地进行更新)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM