简体   繁体   English

使用jQuery单击时将文本追加到div元素中

[英]Append text into div element when click using jquery

Using the below code I append some input elements into the #cls div. 使用以下代码,我将一些input元素附加到#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 您需要查看点击是否确实发生在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. 如果您使用.after()方法而不是.append(),则该文本框将显示在#cls div外部,因此单击该文本框不会导致添加新的文本框。

Some code 一些代码

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

Try it out 试试看

use jQuery's one method. 使用jQuery的一种方法。 it will register click handler only once. 它只会注册一次点击处理程序。

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

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

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