简体   繁体   English

jQuery:查找文本并替换为HTML

[英]jQuery: Find text and replace with HTML

I try to find and replace text (using jQuery). 我尝试查找和替换文本(使用jQuery)。 Actually I'm trying to add a span element around the text. 实际上我正在尝试在文本周围添加span元素。 I should also be able to remove the span again without losing the text inside. 我也应该能够再次移除跨度而不会丢失内部文本。

For example, let's say I have the following situation to start with: 例如,假设我有以下情况开始:

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

And I want to be able to do this dynamically using jQuery/JavaScript: 我希望能够使用jQuery / JavaScript动态执行此操作:

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

I should also be able to remove the span.marked and get back to the first result. 我也应该能够删除span.marked并返回第一个结果。

The problem however is that I want to do this on all text inside a container with multiple children and subchildren and so on. 但问题是我想在具有多个子节点和子节点的容器内的所有文本上执行此操作,依此类推。

The code I got so far will do the following and that is not what I want: 到目前为止我得到的代码将执行以下操作,这不是我想要的:

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

I want to do this for ALL text on the page, not just the first it finds. 我想对页面上的所有文本执行此操作,而不仅仅是它找到的第一个文本。

EDIT: my code so far for doing this: 编辑:我的代码到目前为止这样做:

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

word is a string with the text to wrap spans around. word是一个包含文本的字符串。

To wrap a search string in html you can use something like this: 要在html中包装搜索字符串,您可以使用以下内容:

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

and to remove it, you can use something like this: 并删除它,你可以使用这样的东西:

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

Yes this is a pretty crude way of doing it but it should work. 是的,这是一种非常粗暴的做法,但它应该有效。

EDIT: as pointed out by @user3558931, the word needs to be a variable. 编辑:正如@ user3558931指出的那样,这个词必须是一个变量。

To wrap a search string in html you can use something like this: 要在html中包装搜索字符串,您可以使用以下内容:

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

and to remove it, you can use something like this: 并删除它,你可以使用这样的东西:

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

EDIT: A glitch in the above code, see the fixed code in this fiddle: http://jsfiddle.net/thePav/7TNk6/21/ 编辑:上面代码中的一个小故障,请看这个小提琴中的固定代码: 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>')); 
});

Don't use a regular expression. 不要使用正则表达式。 Use DOM traversal, which will be much more reliable, faster and less destructive (event handlers are not destroyed, for example). 使用DOM遍历,这将更可靠,更快速,破坏性更小(例如,事件处理程序不会被破坏)。

See https://stackoverflow.com/a/10618517/96100 for a simple example. 有关简单示例,请参阅https://stackoverflow.com/a/10618517/96100

Alternatively, you could use the following: 或者,您可以使用以下内容:

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

This doesn't cover removing the spans afterwards but that is a reasonably simple matter. 这不包括之后移除跨度,但这是一个相当简单的事情。 Something like the following (untested): 类似以下内容(未经测试):

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();

I believe the regular expression needs to be adjusted so it does not pick <span or any other HTML tag for that matter. 我认为需要调整正则表达式,因此它不会选择<span或任何其他HTML标记。 I would like to suggest the RegExp: 我想建议RegExp:

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

And the replacement: 并且替换:

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

And can be reversed by using the code (Click button in demo below): 并且可以通过使用代码反转(下面的演示中的点击按钮):

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

JS FIDDLE DEMO JS FIDDLE DEMO

OTHER DEMO 其他的演示

var mark = function(word){
    return function(){
        this.innerHTML = this.innerHTML.replace(word,'' + word + '');
    }
};
$('span').each(mark('span'));

Try using following: 尝试使用以下:

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

If that is your problem that is. 如果这是你的问题。 Otherwise, please clarify, what exactly isn't working as it is supposed to? 否则,请澄清,究竟什么不能正常工作?

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM