Javascript 使用 jQuery 将一个标签替换为另一个

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7093417/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:49:44  来源:igfitidea点击:

Using jQuery to replace one tag with another

javascriptjqueryreplace

提问by jon

Goal:

目标:

Using jQuery, I'm trying to replace all the occurrences of:

使用 jQuery,我试图替换所有出现的:

<code> ... </code>

with:

和:

<pre> ... </pre>

My solution:

我的解决方案:

I got as far as the following,

我得到了以下内容,

$('code').replaceWith( "<pre>" + $('code').html() + "</pre>" );

The problem with my solution:

我的解决方案的问题:

but the issues is that it's replacing everything between the (second, third, fourth, etc)"code" tags with the content between the first"code" tags.

但问题是它正在用第一个“代码”标签之间的内容替换(第二、第三、第四等)“代码”标签之间的所有内容。

e.g.

例如

<code> A </code>
<code> B </code>
<code> C </code>

becomes

变成

<pre> A </pre>
<pre> A </pre>
<pre> A </pre>

I think I need to use "this" and some sort of function but I'm afraid I'm still learning and don't really understand how to piece a solution together.

我想我需要使用“这个”和某种功能,但恐怕我仍在学习,并不真正了解如何将解决方案拼凑在一起。

回答by Felix Kling

You can pass a function to .replaceWith[docs]:

您可以将函数传递给.replaceWith[docs]

$('code').replaceWith(function(){
    return $("<pre />", {html: $(this).html()});
});

Inside the function, thisrefers to the currently processed codeelement.

在函数内部,this指的是当前处理的code元素。

DEMO

演示

Update:There is no big performance difference, but in case the codeelements have other HTML children, appending the children instead of serializing them feels to be more correct:

更新:没有什么大的性能差异,但万一code元素具有其他HTML孩子,追加的孩子而序列化他们感觉是更正确的:

$('code').replaceWith(function(){
    return $("<pre />").append($(this).contents());
});

回答by Jens Roland

This is much nicer:

这更好:

$('code').contents().unwrap().wrap('<pre/>');

Though admittedly Felix Kling's solutionis approximately twice as fast:

诚然,Felix Kling 的解决方案大约快两倍

回答by pimvdb

It's correct that you'll always obtain the first code's contents, because $('code').html()will always refer to the first element, wherever you use it.

您将始终获得 firstcode的内容是正确的,因为$('code').html()无论您在何处使用它,都将始终引用第一个元素。

Instead, you could use .eachto iterate over all elements and change each one individually:

相反,您可以使用.each迭代所有元素并单独更改每个元素:

$('code').each(function() {
    $(this).replaceWith( "<pre>" + $(this).html() + "</pre>" );
    // this function is executed for all 'code' elements, and
    // 'this' refers to one element from the set of all 'code'
    // elements each time it is called.
});

回答by Kokos

Try this:

尝试这个:

$('code').each(function(){

    $(this).replaceWith( "<pre>" + $(this).html() + "</pre>" );

});

http://jsfiddle.net/mTGhV/

http://jsfiddle.net/mTGhV/

回答by Tae-Sung Shin

How about this?

这个怎么样?

$('code').each(function () {
    $(this).replaceWith( "<pre>" + $(this).html() + "</pre>" );
});

回答by tewathia

Building up on Felix's answer.

以菲利克斯的回答为基础。

$('code').replaceWith(function() {
    var replacement = $('<pre>').html($(this).html());
    for (var i = 0; i < this.attributes.length; i++) {
        replacement.attr(this.attributes[i].name, this.attributes[i].value);
    }
    return replacement;
});

This will reproduce the attributes of the codetags in the replacement pretags.

这将code在替换pre标签中重现标签的属性。

Edit: This will replace even those codetags that are inside the innerHTMLof other codetags.

编辑:这甚至会替换其他标签code内的那些标签。innerHTMLcode

function replace(thisWith, that) {
    $(thisWith).replaceWith(function() {
        var replacement = $('<' + that + '>').html($(this).html());
        for (var i = 0; i < this.attributes.length; i++) {
            replacement.attr(this.attributes[i].name, this.attributes[i].value);
        }
        return replacement;
    });
    if ($(thisWith).length>0) {
        replace(thisWith, that);
    }
}

replace('code','pre');

回答by Simon

As of jQuery 1.4.2:

从 jQuery 1.4.2 开始:

$('code').replaceWith(function(i,html) {
  return $('<pre />').html(html);
});?

You can then select the new elements:

然后您可以选择新元素:

$('pre').css('color','red');

Source: http://api.jquery.com/replaceWith/#comment-45493689

来源:http: //api.jquery.com/replaceWith/#comment-45493689

jsFiddle: http://jsfiddle.net/k2swf/16/

jsFiddle:http: //jsfiddle.net/k2swf/16/

回答by Fabian von Ellerts

Another short & easy way:

另一种简短而简单的方法:

$('code').wrapInner('<pre />').contents();

回答by Salman A

If you were using vanilla JavaScript you would:

如果您使用的是 vanilla JavaScript,您会:

  • Create the new element
  • Move the children of old element into the new element
  • Insert the new element before the old one
  • Remove the old element
  • 创建新元素
  • 将旧元素的子元素移动到新元素中
  • 在旧元素之前插入新元素
  • 删除旧元素

Here is jQuery equivalent of this process:

这是这个过程的 jQuery 等价物:

$("code").each(function () {
    $("<pre></pre>").append(this.childNodes).insertBefore(this);
    $(this).remove();
});

Here is the jsperf URL:
http://jsperf.com/substituting-one-tag-for-another-with-jquery/7

这是 jsperf 网址:http://jsperf.com/substituting-one-tag-for-another-with-jquery/7

PS: All solutions that use .html()or .innerHTMLare destructive.

PS:所有使用.html().innerHTML具有破坏性的解决方案。

回答by Arnab C.

You could use jQuery's html function. Below is a sample the replaces a code tag with a pre tag while retaining all of the attributes of the code.

你可以使用 jQuery 的 html 函数。下面是一个示例,它用 pre 标记替换代码标记,同时保留代码的所有属性。

    $('code').each(function() {
        var temp=$(this).html();
        temp=temp.replace("code","pre");
        $(this).html(temp);
    });

This could work with any set of html element tags that needed to be swapped while retaining all the attributes of the previous tag.

这适用于需要交换的任何 html 元素标签集,同时保留前一个标签的所有属性。