为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

湖上湖 2019-10-26 13:02:47
目标:使用jQuery,我试图替换所有出现的情况:<code> ... </code>与:<pre> ... </pre>我的解决方案:我了解到以下内容:$('code').replaceWith( "<pre>" + $('code').html() + "</pre>" );我的解决方案的问题:但是问题在于它用第一个 “ code”标签之间的内容替换了(第二,第三,第四等)“ code”标签之间的所有内容。例如<code> A </code><code> B </code><code> C </code>变成<pre> A </pre><pre> A </pre><pre> A </pre>我想我需要使用“ this”和某种功能,但是恐怕我还在学习,并且不太了解如何将解决方案组合在一起。
查看完整描述

3 回答

?
Cats萌萌

TA贡献1805条经验 获得超9个赞

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


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

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

});

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


演示


更新:并没有很大的性能差异,但是如果code元素具有其他HTML子元素,则附加子元素而不是对其进行序列化会更正确:


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

    return $("<pre />").append($(this).contents());

});


查看完整回答
反对 回复 2019-10-26
?
慕村225694

TA贡献1880条经验 获得超4个赞

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


相反,您可以.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.

});


查看完整回答
反对 回复 2019-10-26
?
30秒到达战场

TA贡献1828条经验 获得超6个赞

建立在Felix的答案上。


$('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;

});

这将code在替换pre标签中复制标签的属性。


编辑:这将取代甚至code是里面的标签innerHTML等的code标签。


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


查看完整回答
反对 回复 2019-10-26
  • 3 回答
  • 0 关注
  • 3696 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信