在按钮上显示/隐藏Divs单击:不按预期工作?

时间:2018-06-09 22:18:59

标签: javascript jquery

结果:http://unidrones.co.za/PixieStudio/quotations.php

简单地说,我"添加新层"然后"删除等级"然后尝试添加它,没有任何反应。以下是两个涉及的JavaScript函数:

/*Remove Tier on Button Click*/
$(".button").click(function(){
    $(this).parent().find('select').prop('selectedIndex',0); //erase prices for this tier
    $(this).parent().hide();
    updateHandler();
});

/*Add New Tier on Button Click*/
$('#tier2, #tier3, #tier4, #tier5, #tier6').hide();
var count = 2, countMax = 6;
function addtier() {
  if(count > countMax) {
    return;
  }
  $('#tier' + count + '').fadeIn(1000);
  count++;
}

HTML(缩写):

<div id="tier2">
<button type="button" class="button">Remove</button>
...
</div>

<div id="tier3">
<button type="button" class="button">Remove</button>
...
</div>

<div id="tier4">
<button type="button" class="button">Remove</button>
...
</div>

我不确定如何准确地解释这个问题。您可能会理解,如果您转到该链接并尝试添加/删除层。

为什么在我删除它们后会重新出现这些层?

2 个答案:

答案 0 :(得分:1)

这是因为你的最大数量为6 - 一旦你添加了所有6层,你要添加层,除非你再次重置count变量。你应该做的是:

  • 每当添加一个层时增加count
  • 每当删除某个层时递减count (您错过了此部分)

此外,您应该删除它们(使用.remove()),而不是隐藏它们,这样您就不会有重复的ID:

/*Track tiers*/
var count = 2, countMax = 6;

/*Remove Tier on Button Click*/
$(".button").click(function(){
    $(this).parent().find('select').prop('selectedIndex',0);
    $(this).parent().remove();

    // Remember to decrement count!
    count--;

    // Optional: you might want to ensure that
    // count can go as low as 2, but not lower
    count = Math.max(2, count);

    updateHandler();
});

/*Add New Tier on Button Click*/
$('#tier2, #tier3, #tier4, #tier5, #tier6').hide();
function addtier() {
  if(count > countMax) {
    return;
  }
  $('#tier' + count + '').fadeIn(1000);
  count++;
}

答案 1 :(得分:0)

这是另一种方法,它只使用CSS选择器,并且不需要跟踪显示的数量(因为它隐含在DOM中)。 (对你的java.util.Date和类有一些自由,所以这可能不适合你现有的代码)

&#13;
&#13;
id
&#13;
$(function() {
  $('#hide').click( function() { $('.tier:not(:hidden)').last().hide() });
  $('#show').click( function() { $('.tier:hidden').first().show() });
});
&#13;
&#13;
&#13;

相关问题