I am creating a dynamic select box, on change a text section will get populated with data. I would rather have the data set to some text as opposed to being append.
我正在创建一个动态选择框,在更改文本部分时将填充数据。我宁愿将数据集设置为某些文本而不是追加。
For example:
This function gets called when a select box is changed:
更改选择框时会调用此函数:
function createDetails(...) {
var details = document.getElementById("detailsDIV");
var docFragment = document.createDocumentFragment();
containerDiv = document.createElement("div");
// Create five div sections with the text for the details section
var nameTextNode = createTextDivSect(nameStr);
var phoneTextNode = createTextDivSect("Phone: " + phoneStr);
var faxTextNode = createTextDivSect("Fax: " + faxStr);
var websiteTextNode = createTextDivSect("Website: " + websiteStr);
var emailTextNode = createTextDivSect("Email: " + emailStr);
// Append the text sections to the container DIV
containerDiv.appendChild(nameTextNode);
containerDiv.appendChild(phoneTextNode);
containerDiv.appendChild(faxTextNode);
// Add the container div to the doc fragment
docFragment.appendChild(containerDiv);
// Add the doc fragment to the div
details.appendChild(docFragment);
}
////
With this approach, it is assuming I am appending to a section. Is there a way I can just SET the child. I guess I could remove the child and then set it. But I figure that would waste resources.
使用这种方法,假设我附加到一个部分。有没有办法可以设置孩子。我想我可以删除孩子然后设置它。但我认为这会浪费资源。
1 个解决方案
#1
If you want to set an entire div at once without using innerHTML, you can use replaceChild()
:
如果要在不使用innerHTML的情况下一次设置整个div,可以使用replaceChild():
function createDetails(...) {
var details = document.getElementById("detailsDIV");
var docFragment = document.createDocumentFragment();
// Process docFragment here...
var parentNode = details.parentNode;
parentNode.replaceChild(docFragment, details);
}
#1
If you want to set an entire div at once without using innerHTML, you can use replaceChild()
:
如果要在不使用innerHTML的情况下一次设置整个div,可以使用replaceChild():
function createDetails(...) {
var details = document.getElementById("detailsDIV");
var docFragment = document.createDocumentFragment();
// Process docFragment here...
var parentNode = details.parentNode;
parentNode.replaceChild(docFragment, details);
}