我没有给出答案,所以希望有人可以帮助我。
我正在尝试在文本中的子字符串或位置前后无损地插入HTML,以创建新的内联元素或包装现有文本。我将只使用innerHTML并已完成此操作,但我真的很想保留可能绑定(bind)到该特定DOMNode的可能的事件侦听器。是否有一种方法或Element的原型(prototype)将textNodes视为单独的项目,可以让我在HTML之前或之后附加HTML?
代码可能会像这样运行:
var testParagraph = document.getElementById("TestParagraph");
/**
text nodes would represent each item
that has been seperated by a space, for example
**/
testParagraph.insertBefore(document.createElement("span"), testParagraph.textNodes[3])
谢谢你的时间!
最佳答案
如果要在文本中插入dom元素,则不会出现事件处理程序问题,因为事件处理程序无法绑定(bind)到文本本身。在不破坏任何事件处理程序的情况下,更改DOM元素的内容是可能的,并且比您想象的要容易。
function insertAtStringPos(el, pos, insertable) {
if(!el.children.length) {
var text = el.outerText;
var beginning = document.createTextNode(text.substr(0, pos));
var end = document.createTextNode(text.substr(pos - text.length));
while (el.hasChildNodes()) {
el.removeChild(el.firstChild);
}
el.appendChild(beginning);
el.appendChild(insertable);
el.appendChild(end);
}
}
示例:http://jsfiddle.net/9a8rxhp4/