javascript - 如何在 div 中重复添加 html,但保留预先存在的 html?

标签 javascript jquery replace

使用 jQuery 的 Javascript,我想一遍又一遍地将文本字符串替换为 html 标记,而不会丢失之前的 html。

FIDDLE

<p>This is <i id="text">text</i> and more text</p>

这是文本和更多文本

function rep() {
    var t = $('p').text().replace('text', '<b>html</b>'); 
    $('p').html(t);
}

理想情况下它看起来像:

<p>This is <i id="text"><b>html</b></i> and more <b>html</b></p>

这是html以及更多html

我不想更改预先存在的 html。 <i id="text">无论我运行该函数多少次,都应该保留在 html 中。 .html().replace(..不起作用,因为它会捕获 id="text" 。谢谢。

最佳答案

您需要使用 .html() 获取旧值,而不是 .text(),因为后者忽略了所有 HTML 标记。您可以在一次调用中完成此操作,使用函数根据旧值计算替换值:

function rep() {
    $('p').html(function(i, oldhtml) {
        return oldhtml.replace(/(<[^>]*)?text/g, function($0, $1) {
            return $1 ? $0 : '<b>html</b>';
        });
    });
}

请注意,您必须使用带有 g 修饰符的正则表达式才能在字符串中执行多次替换。负向后查找是排除 id="text" 的正常方法,但这不可用。我使用了 Javascript: negative lookbehind equivalent? 中的解决方法

关于javascript - 如何在 div 中重复添加 html,但保留预先存在的 html?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20692245/

相关文章:

python - 导入错误: cannot import name 'RegexpReplacer'

Javascript 对象顺序不正确

javascript - 如何将 ArrayBuffer 从 JS 传递到 AssemblyScript/Wasm?

javascript - jQuery 通过多个行情轮换

jQuery 悬停多次触发。没有一种解决方案有帮助

将TR移动到另一个表后jquery的hover()和click()不起作用

javascript - 为新数组赋值

javascript - Ajax/Json 错误 : "A circular reference was detected while serializing an object of type" when trying to bring a list

php - mySQL 表中撇号替换为 '

sql-server - 如何替换分号?