jQuery:查找文本并替换为HTML

jQuery: Find text and replace with HTML

本文关键字:替换 HTML 文本 查找 jQuery      更新时间:2023-09-26

我尝试查找和替换文本(使用jQuery(。实际上,我正试图在文本周围添加一个span元素。我还应该能够再次删除跨度,而不会丢失里面的文本。

例如,假设我从以下情况开始:

<span>This is a span element</span>

我希望能够使用jQuery/JavaScript:动态地做到这一点

<span>This is a <span class="marked">span</span> element</span>

我也应该能够删除span.marked并返回到第一个结果。

然而,问题是,我想对一个包含多个子级和子级等的容器中的所有文本执行此操作

到目前为止,我得到的代码将执行以下操作,这不是我想要的:

<<span class="marked">span</span>>This is a <span class="marked">span</<span class="marked">span</span> element</span>

我想对页面上的所有文本都这样做,而不仅仅是它找到的第一个文本。

编辑:到目前为止我的代码:

var re = new RegExp(word, 'g');
$('.container').html($('.container').html().replace(re, '<span class="marked">' + word + '</span>'));

单词是一个字符串,包含要换行的文本。

要用html包装搜索字符串,可以使用以下内容:

$('span:contains("word")').html().replace('word', '<span class="marked">word</span>');

要删除它,你可以使用这样的东西:

$('span:contains("word")').html().replace('<span class="marked">word</span>', 'word');

是的,这是一种相当粗糙的方法,但它应该有效。

编辑:正如@user3558931所指出的,单词需要是一个变量。

要用html包装搜索字符串,可以使用以下内容:

$('span:contains("' + str + '")').html().replace(str, '<span class="marked">' + str + '</span>');

要删除它,你可以使用这样的东西:

$('span:contains("' + str + '")').html().replace('<span class="marked">' + str + '</span>', str);

编辑:上面代码中的一个小故障,请参阅此小提琴中的修复代码:http://jsfiddle.net/thePav/7TNk6/21/

$('.container p').each(function() {
    var text = $(this).text();
    $(this).html(text.replace('word', '<strong><span class="accordion">word </span></strong>')); 
});
不要使用正则表达式。使用DOM遍历,它将更可靠、更快、破坏性更小(例如,事件处理程序不会被破坏(。

请参阅https://stackoverflow.com/a/10618517/96100作为一个简单的例子。

或者,您可以使用以下方法:

http://james.padolsey.com/javascript/replacing-text-in-the-dom-solved/

这不包括之后移除跨度,但这是一个相当简单的问题。类似以下内容(未经测试(:

function replaceWithOwnChildren(el){
    var parent = el.parentNode;
    while (el.hasChildNodes()) {
        parent.insertBefore(el.firstChild, el);
    }
    parent.removeChild(el);
}
// Create a non-live standard array of spans
var spans = [].slice.call(document.getElementsByTagName("span"), 0);
for (var i = 0, len = spans.length; i < len; ++i) {
    if (spans[i].className == "marked") {
        replaceWithOwnChildren(spans[i]);
    }
}
// Glue together any adjacent text nodes
document.normalize();

我认为正则表达式需要调整,这样它就不会选择<span或任何其他HTML标记。我想建议RegExp:

var re = new RegExp('[^<''/](' + word + ')', 'g');

以及替代品:

$('.container').each(function() {
    $(this).html( $(this).html().replace( re, ' <span class="marked">$1</span>' ) );
});

并且可以使用代码反转(点击下面演示中的按钮(:

$('button.undo').on( 'click', function() {
    $('.container').find( 'span.marked' ).each(function() {
        $(this).replaceWith( word );
    });
});

JS FIDDLE演示

其他演示

var mark=函数(word({return函数(({this.innerHTML=this.inner HTML.replace(单词,'''+word+''(;}};$('span'(.每个(标记('span'((

尝试使用以下内容:

$('.container').forEach(function(){ 
    $(this).html().... 
})

如果这是你的问题,那就是。否则,请澄清,到底是什么不起作用?

var span = document.getElementsByTagName("span")[0];
span.innerHTML = span.innerHTML.replace(/span/g, "<span class='"marked'">span</span>");

http://jsfiddle.net/7TNk6/1/