使用JavaScript显示/隐藏<div>

5

我写了一段简单的JavaScript代码,用于在点击另一个<div>后显示隐藏的<div>。一切都正常工作,但是当点击其中一个<div>中的复选框时,隐藏的那个会立即显示并隐藏。

$(document).ready(function() {
  $('#click1').click(function() {
    if ($('#hidden1').is(':hidden')) {
      $('#hidden1').show(500);
    } else {
      $('#hidden1').hide(500);
    }
  });
});
.divCell {
  width: 500px;
  height: 35px;
  margin: 2px 0;
  display: inline-block;
  background-color: #D4F78F;
}
.checkbox_div {
  width: 25px;
  position: relative;
  margin: 5px;
  float: left;
}
input[type="checkbox"] {
  display: none;
}
input[type="checkbox"] + label {
  width: 25px;
  height: 25px;
  cursor: pointer;
  position: absolute;
  top: 0;
  left: 0;
  background-color: white;
  border-radius: 4px;
}
.div_name_divcell {
  line-height: 35px;
  width: auto;
  float: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div class="divCell" id="click1">
  <div class="checkbox_div">
    <input type="checkbox" id="checkbox1">
    <label for="checkbox1"><span></span>
    </label>
  </div>
  <div class="div_name_divcell">Name1</div>
</div>

<div id="hidden1" style="display: none;">
  hidden text
</div>

Fiddle: https://jsfiddle.net/mamzj4tw/

2个回答

3
event.preventDefault添加到您的代码中。
  $(document).ready(function() {
  $('#click1').click(function(event) {
  event.preventDefault();


        if ($('#hidden1').is(':hidden')) {

       $('#hidden1').show(500);
    } else {

       $('#hidden1').hide(500);
    }
  });
});

这里有一个 Fiddle: https://jsfiddle.net/mamzj4tw/1/


1
你应该在回答中发布你的代码,而不是依赖第三方网站。 - j08691

0

你可以只使用return false;

$(document).ready(function() {
  $('#click1').click(function() {
    if ($('#hidden1').is(':hidden')) {
      $('#hidden1').show(500);
    } else {
      $('#hidden1').hide(500);
    }
    return false;
  });
});

https://jsfiddle.net/shadiq_aust/m91wf79y/1/


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接