简体   繁体   中英

Append text into div element when click using jquery

Using the below code I append some input elements into the #cls div. But when I try to type inside the input also new input add. I only need new input when I click "click" text. Can anyone help me. Thank you

$('#cls').click(function() {
    var add="<input type="text">"
    $(#cls).append(add);
});
<div id="cls">click</div>

You need to see whether the click actually happened in the div

 $('#cls').click(function(e) { if ($(e.target).is(this)) { //or !$(e.target).is('input') var add = '<input type="text">'; $(this).append(add); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="cls">click</div> 

Append your input to parent element:

 var clicked= false; $('#cls').click(function() { if(!clicked){ var add="<input type='text'>"; $(this).parent().append(add); clicked = true; } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id='cls'>click</div> 

If you user .after() method instead of .append() the textbox would appear outside the #cls div and hence clicking the textbox wouldn't cause adding a new one.

Some code

$('#cls').click(function() {
  var add="<input type='text'>";
  $('#cls').after(add);
});

Try it out

use jQuery's one method. it will register click handler only once.

$('#cls').one("click", function(e) {
    var add = '<input type="text">';
    $(this).append(add);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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