我想在外部 javascript 文件中创建一个函数,以便稍后重用(即,一个足够通用的模块化函数,可以在任何需要它的 javascript 中使用)。我想用纯 JavaScript 来完成此操作,而不是使用 jQuery 或innerHTML。
我希望这个模块化函数执行以下操作: 1)删除子元素 2)用新的子值替换这个子项
例如,假设您有以下代码:
<p id="removeMe">This text needs to be removed</p>
<p id="nextPara">This is the paragraph that follows the replaced paragraph</p>
所以我需要:
1) parentNode.removeChild(removeMe);
2) var replacementParagraph = document.createElement('p');
3) var replacementParagraphText =document.createTextNode("This is the replacementParagraph text);
4) replacementParagraph.appendChild(replacementParagraphText);
现在我只需要弄清楚如何编写如下所示的模块化函数:
function removeReplace (parameter, parameter) {
1) remove the child of the paragraph with the id of "removeMe"
2) use insertBefore(newText, nextPara) to replace the child that was removed in step 1
}
非常感谢你的帮助,杰森
最佳答案
哦,这更容易,因为这个函数本身已经存在:.replaceChild()
。实际上你已经有了算法,你只需要用 javascript 编写它:
function replaceElementByParagraph(id, text) {
var toremove = document.getElementById(id);
if (!toremove) // in case no element was found:
return false; // abort
var para = document.createElement('p');
para.appendChild(document.createTextNode(text));
return toremove.parentNode.replaceChild(para, toremove);
}
关于javascript removeChild 然后使用 insertBefore 将其替换为新文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12889239/