[英]How do you clear a <div>s contents with javascript?
我有<div id="editform"></div>
。 我當前有一些html。 如何清除html並在其中插入完全不同的html?
我嘗試了這個,但它不起作用:
document.getElementById('editform').innerHTML = "";
document.getElementById('editform').innerHTML = "<input type=\"text\" placeholder=\"Title\" id=\"title\" name=\"title\" style=\"display:
block;\"><textarea rows=\"10\" style=\"display: block;\" id=\"textLoc\" placeholder=\"Text to test\"cols=\"50\"></textarea>";
有任何想法嗎?
var cell = document.getElementById("cell");
if ( cell.hasChildNodes() )
{
while ( cell.childNodes.length >= 1 )
{
cell.removeChild( cell.firstChild );
}
}
我建議使用document.createNode(...)
和document.appendChild(...)
將div添加到div中,而不是將其添加為innerHTML。 改變innerHTML往往是錯誤的。
只要您從新的HTML字符串中刪除(或轉義)換行符,您的代碼就可以正常工作。
示例: http : //jsbin.com/olabo4/
所以改變這個:
document.getElementById('editform').innerHTML = "<input type=\"text\" placeholder=\"Title\" id=\"title\" name=\"title\" style=\"display:
block;\"><textarea rows=\"10\" style=\"display: block;\" id=\"textLoc\" placeholder=\"Text to test\"cols=\"50\"></textarea>";
對此:
document.getElementById('editform').innerHTML = "<input type=\"text\" placeholder=\"Title\" id=\"title\" name=\"title\" style=\"display: block;\"><textarea rows=\"10\" style=\"display: block;\" id=\"textLoc\" placeholder=\"Text to test\"cols=\"50\"></textarea>";
或這個:
document.getElementById('editform').innerHTML = "<input type=\"text\" placeholder=\"Title\" id=\"title\" name=\"title\" style=\"display: \
\
block;\"><textarea rows=\"10\" style=\"display: block;\" id=\"textLoc\" placeholder=\"Text to test\"cols=\"50\"></textarea>";
那應該有用......也許問題出在其他地方?
如果要刪除所有子節點,請嘗試以下操作:
function removeChildren(obj) {
while(obj.hasChildNodes()) { obj.removeChild(obj.lastChild); }
};
像這樣稱呼它:
removeChildren(document.getElementById('editform'))
;
document.getElementById('editform').innerHTML = "";
這應該工作。
順便說一句,你不需要逃避“在字符串中,你可以在字符串內使用'。
另外,為了讓您的生活更輕松,我建議使用一些Javascript庫,如JQuery或Mootools,這樣您的DOM操作更容易,並且跨瀏覽器兼容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.