我希望我的div在增加元素时显示块

时间:2018-04-12 14:50:09

标签: jquery html

我想通过点击“添加”来增加我的div display: block。按钮。

我正在使用jQuery。我的问题是,当我点击添加框时,它不会更改display



var num = 0;

if ($('.selected-news').is(':empty')) {
  $('.news-pick-box').css("display", "none");
} else {
  $('.news-pick-box').css("display", "block");
}

$('.addbutton').click(function() {
  $(".selected-news").html(function(i, val) {
    return +val + 1
  });
})

$('.subbutton').click(function() {
  $(".selected-news").html(function(i, val) {
    return +val - 1
  });
})

.addbutton,
.subbutton {
  padding: 10px 20px;
  background-color: black;
  color: white;
  font-size: 30px;
  width: 200px;
  margin: 10px;
  cursor: pointer;
}

.news-pick-box {
  width: 100%;
  background-color: red;
  color: white;
  font-weight: bold;
  height: 30px;
}

p.news-picked {
  text-align: center;
  text-transform: uppercase;
  line-height: 30px;
  font-size: 20px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="addbutton">
  ADD
</div>
<div class="subbutton">
  SUBTRACT
</div>
<div class="news-pick-box">
  <p class="news-picked">You have selected <span class="selected-news"></span> news</p>
</div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:0)

var num = 0;
if ($('.selected-news').is(':empty')) {
  $('.news-pick-box').css("display", "none");
} else {
  $('.news-pick-box').css("display", "block");
}
$('.addbutton').click(function(){
  if (!$('.news-pick-box').is(":visible")) {
    $('.news-pick-box').show();
  }
  num++;
  $('.selected-news').html(num);
})
$('.subbutton').click(function(){
  if (num > 0) {
    num--;
  }
  if (num === 0) {
    $('.news-pick-box').hide();
  }
  $('.selected-news').html(num);
})
.addbutton, .subbutton {
  padding: 10px 20px;
  background-color: black;
  color: white;
  font-size: 30px;
  width: 200px;
  margin: 10px;
  cursor: pointer;
}
.news-pick-box {
  width: 100%;
  background-color: red;
  color: white;
  font-weight: bold;
  height: 30px;
}
p.news-picked {
  text-align: center;
  text-transform: uppercase;
  line-height: 30px;
  font-size: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="addbutton">ADD</div>
<div class="subbutton">SUBTRACT</div>
<div class="news-pick-box">
	<p class="news-picked">You have selected <span class="selected-news"></span> news</p>
</div>

答案 1 :(得分:0)

var num = 0;
function refreshSelectedNewsContent(){
 $(".selected-news").html((num>0?num:""));
    if ($('.selected-news').is(':empty')) {
    $('.news-pick-box').css("display", "none");
} else {
    $('.news-pick-box').css("display", "block");
}
}
$('.addbutton').click(function(){ num++; refreshSelectedNewsContent();  })
$('.subbutton').click(function(){if(num>0) num--; refreshSelectedNewsContent(); })
refreshSelectedNewsContent();

请尝试此代码。 它确保num不能为负数,只有当num为正时才显示该块。