简体   繁体   English

如何在点击时删除div并显示另一个div

[英]How to remove a div on click and show another div

I want to show a hidden div once a user click on a text input and remove the div that was displayed, but if the user click again on the text input I don't want the div that just got deleted to show up again. 一旦用户单击文本输入并删除显示的div,我想显示一个隐藏的div,但是如果用户再次单击文本输入,我不希望刚刚删除的div再次显示。

I have tried this so far: 到目前为止,我已经尝试过了:

<div id="div1"> Have to be remove on click</div>

<div id="div2">Hidden on page load and show on click</div>

<input type="text" id="input" placeholder="click here" />

.

$(function(){
    $("#div2").hide();
    $("#div1").show();
    $("#input").on("click", function(){

      $(" #div2").toggle();

    });

});

I think this below snippet solves your problem, please let me know if this helps you! 我认为下面的代码片段可以解决您的问题,如果有帮助,请告诉我!

 $(function(){ $("#div2").hide(); $("#div1").show(); $("#input").on("click", function(){ $("#div1").hide(); $(" #div2").show(); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="div1"> Have to be remove on click</div> <div id="div2">Hidden on page load and show on click</div> <input type="text" id="input" placeholder="click here" /> 

I want to show a hidden div once a user click on a text input and remove the div that was displayed 我想在用户单击文本输入并删除显示的div后显示一个隐藏的div

Add a focus event to the input focus事件添加到input

$("#input").on("focus", function() {
  $("#div1").remove(); //div1 is removed
  $(" #div2").show(); //hidden div is shown
});

$("#input").on("blur", function() {
  $(" #div2").hide(); //div2 is hidden again
});

Demo 演示

 $("#input").on("focus", function() { $("#div1").remove(); //div1 is removed $(" #div2").show(); //hidden div is shown }); $("#input").on("blur", function() { $(" #div2").hide(); //div2 is hidden again }); 
 #div2 { display: none; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="div1"> Have to be remove on click</div> <div id="div2">Hidden on page load and show on click</div> <input type="text" id="input" placeholder="click here" /> 

$(document).ready(function(){ 
$("#input").click(function(){
      $("#div1").toggle();
    }); 
});

Don't make two buttons, one for hide and other one for show . 不要做两个按钮,一个用于隐藏 ,另一个用于显示 Make one button and use toggle() . 制作一个按钮并使用toggle() Now that's all you need ... This will definitely work. 现在,这就是您所需要的...肯定可以。

Read this it will help you https://www.javatpoint.com/jquery-toggle 阅读此内容将对您有所帮助https://www.javatpoint.com/jquery-toggle

:) :)

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

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