簡體   English   中英

將html(text)附加到元素而不影響同級?

[英]Append html(text) to element without affecting siblings?

我總是使用appendChild向其他元素添加內容,因為如果使用:

innerHTML +=  'added stringgggggggggg';

然后這會將動態元素(例如<form> )與填充的值弄亂(將字段值重置為空)。

有沒有更短的方法可以在沒有appenChild和不使用JQuery的情況下向元素添加smth?

您可以使用element.insertAdjacentHTML()求值並將原始HTML字符串附加到元素。

element.insertAdjacentHTML('beforeend', '<p>put me inside at the end</p>');

通過更改position屬性,您可以在元素之前,元素之后,元素內部的開頭或元素的結尾插入。

<!-- beforebegin -->
<p>
  <!-- afterbegin -->
  foo
  <!-- beforeend -->
</p>
<!-- afterend -->

innerHTML不同, insertAdjacentHTML()不會導致瀏覽器不會重新評估您要注入的整個DOM節點,因此將保留表單字段值。

 var parentEl = document.getElementById('parent'); parentEl.insertAdjacentHTML('beforeend', '<p>this paragraph was inserted at the end of the form without affecting the form field values!<p>'); 
 <form id="parent"> <input type="text" value="insert something after form"><br> <input type="text" value="without affecting the values"><br> <input type="text" value="in the form fields"><br> </form> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM