使用 jQuery 将一个标签替换为另一个 [英] Using jQuery to replace one tag with another

查看:33
本文介绍了使用 jQuery 将一个标签替换为另一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目标:

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

... </code>

与:

... </pre>

我的解决方案:

我得到了以下,

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

我的解决方案的问题:

但问题是它用第一个代码"标签之间的内容替换了(第二、第三、第四等)代码"标签之间的所有内容.

例如

</code><代码>B</code><代码>C

变成

</pre><预></pre><预></pre>

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

解决方案

你可以传递一个函数给 .replaceWith [文档]:

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

", {html: $(this).html()});});

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

演示

更新:没有太大的性能差异a>,但如果 code 元素有其他 HTML 子元素,附加子元素而不是序列化它们感觉更正确:

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

Goal:

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

<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.

解决方案

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

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

Inside the function, this refers to the currently processed code element.

DEMO

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

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

这篇关于使用 jQuery 将一个标签替换为另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆