gpt4 book ai didi

javascript - 在 String/String 位置后插入 HTML

转载 作者:可可西里 更新时间:2023-11-01 13:01:59 24 4
gpt4 key购买 nike

我对此没有找到答案,所以希望有人能帮助我。

我正在尝试非破坏性地在文本中的子字符串或位置之前和之后插入 HTML,以创建新的内联元素或包装现有文本。我只想使用 innerHTML 并完成此操作,但我真的很想保留可能绑定(bind)到该特定 DOMNode 的可能事件监听器。是否有一种方法或元素原型(prototype)将 textNode 视为单独的项目,允许我在它之后或之前附加 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/

关于javascript - 在 String/String 位置后插入 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37913055/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com