JQuery部分代码无效隐藏/显示最近

时间:2014-10-02 09:08:28

标签: jquery

嗨我正在尝试在隐藏它之后获取最近的隐藏按钮,所以我正在使用此代码:

//html

<a class="button1" href="#">Button1 Click me</a>
<a class="button2" href="#" style="display:none;">Button2 Here</a>


//JQuery

$('.button1').click(function() {

  $(this).closest(".button1").hide('slow'); //This works (Hides)

  $(this).closest(".button2").show('slow'); //This does not show


});

第一个按钮正在隐藏,但下面的按钮没有显示。

我在这里做错了什么?

4 个答案:

答案 0 :(得分:1)

.closest()遍历DOM,寻找目标的父元素,从目标本身开始(这就是当你尝试显示该元素时它的工作原理)。您要找的是兄弟姐妹(.siblings().prev().next())。

在您的情况下,.next()将是您的选择:

$(function () {
    $('.button1').on('click', function () {
        // Toggle the clicked element display (block/none).
        $(this).toggle('slow');
        // Toggle the clicked element next sibling with class 
        // button2 display (block/none).
        $(this).next('.button2').toggle('slow');
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="button1" href="#">Button1 Click me</a>
<a class="button2" href="#" style="display:none;">Button2 Here</a>
<a class="button1" href="#">Button1 Click me</a>
<a class="button2" href="#" style="display:none;">Button2 Here</a>
<a class="button1" href="#">Button1 Click me</a>
<a class="button2" href="#" style="display:none;">Button2 Here</a>

Demo (jsFiddle)

jQuery API .closest()

jQuery API .siblings()

jQuery API .next()

jQuery API .prev()

答案 1 :(得分:0)

您正试图从点击的按钮向上导航。改为做这样的事情:

$(".button1").hide('slow');
$(".button2").show('slow');

如果你想要切换,你可以这样做:

$('.button1, .button2').click(function() {
    $(this)
        .hide('slow');
        .siblings()
        .show('slow');
});

答案 2 :(得分:0)

我知道你做错了只是把这个片段放在你的代码中并且它可以正常工作

$('.button1').click(function() {
    $(this).hide('slow');
    $(this).next().show('slow');    
}

jsfiddle

答案 3 :(得分:0)

我会选择这样的解决方案。搜索.button是错误的 - 您将搜索整个DOM,而您只对这两个特定按钮感兴趣。要么给它们ID,要么使用下面的代码。

//html
<div class="button-container">
  <a class="button1" href="#">Button1 Click me</a>
  <a class="button2" href="#" style="display:none;">Button2 Here</a>
<div>

//JQuery
$('.button1').click(function() {
  var buttonContainer = $(this).closest(".button-container");
  // you will search for those buttons only inside your container, it will be much faster than plain $('.button1')
  buttonContainer.find('.button1').hide('slow');
  buttonContainer.find('.button2').show('slow');    
});
相关问题