[英]javascript - Create new <li> element with textarea onclick of button
HTML: HTML:
<li><textarea></textarea></li><br><a id="newPoints"></a>
<input type="button" value="+ Add new point" onclick="newPoint();">
CSS (if you need it): CSS(如果需要):
textarea {
font-family: Georgia, 'Times New Roman', Times, serif;
vertical-align: text-top;
width: 300px;
height: 60px;
resize: vertical;
padding: 10px;
}
And Javascript: 和Javascript:
function newPoint() {
var a = document.getElementById("newPoints");
a.innerHTML += '<li><textarea placeholder="To delete this point, select this textbox and press the "Delete" button on your keyboard." onkeydown="if(event.keyCode == 46) { this.parentNode.nextSibling.parentNode.removeChild(this.parentNode.nextSibling); this.parentNode.parentNode.removeChild(this.parentNode); }"></textarea></li><br>';
}
To better visualise, here's a fiddle . 为了更好地可视化,这是一个小提琴 。
So basically, with the code above, I'm trying to make it such that when the user clicks on the button, a new <li>
(that comes with a <br>
after it) that contains a <textarea>
will get created. 因此,基本上,通过上面的代码,我试图将其创建为使得当用户单击按钮时,将创建一个包含<textarea>
的新<li>
(后面带有一个<br>
)。 。 This new <li>
, <textarea>
and the following <br>
will be deleted when the user presses the Delete button on their keyboard while selecting the textarea. 当用户在选择文本区域时按下键盘上的Delete按钮时,新的<li>
, <textarea>
和以下<br>
将被删除。
The problem is that, when the user creates a new <li>
and types some text into its textarea, then create another <li>
, the text from the textarea of the previous <li>
will disappear. 问题是,当用户创建一个新的<li>
和类型的一些文本的文本区域,然后创建另一个<li>
从以前的textarea的文本<li>
将消失。
How can I fix this? 我怎样才能解决这个问题?
Use CreateElement
and appendChild
to add the elements. 使用CreateElement
和appendChild
添加元素。 I think what is happening is when you append to the innerHTML, it is overwriting everything in newPoints
. 我认为正在发生的事情是,当您追加到innerHTML时,它将覆盖newPoints
所有newPoints
。
function newPoint() {
var a = document.getElementById("newPoints");
var l = document.createElement("li");
l.innerHTML = '<textarea placeholder="To delete this point, select this textbox and press the "Delete" button on your keyboard." onkeydown="if(event.keyCode == 46) { this.parentNode.nextSibling.parentNode.removeChild(this.parentNode.nextSibling); this.parentNode.parentNode.removeChild(this.parentNode); }"></textarea>';
var b = document.createElement("br");
a.appendChild(l);
a.appendChild(b);
}
This might help: 这可能会有所帮助:
function newPoint() {
var a = document.getElementById("newPoints");
var newcontent = document.createElement('li');
newcontent.innerHTML = "<textarea placeholder='To delete this point, select this textbox and press the "Delete" button on your keyboard.' onkeydown=\"if(event.keyCode == 46) { this.parentNode.parentNode.removeChild(this.parentNode);}\"></textarea>";
a.appendChild(newcontent);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.