简体   繁体   English

显示/隐藏 <div> 用JavaScript

[英]Showing/hiding <div> with JavaScript

I wrote simple JavaScript to show hidden <div> after clicking another <div> . 我写了简单的JavaScript来显示隐藏<div>单击另一个后<div> Everything works fine however when clicking checkbox in that <div> the hidden one appears and hides instantly. 一切正常但是当点击<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/ 小提琴: https//jsfiddle.net/mamzj4tw/

Add event.preventdefault to your code event.preventdefault添加到您的代码中

  $(document).ready(function() {
  $('#click1').click(function(event) {
  event.preventDefault();


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

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

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

Here is the Fiddle: https://jsfiddle.net/mamzj4tw/1/ 这是小提琴: https//jsfiddle.net/mamzj4tw/1/

You can use just return false; 你可以使用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/ https://jsfiddle.net/shadiq_aust/m91wf79y/1/

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

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