javascript 使用保持 href 和 html 元素的 jquery 将 H3 更改为 H2

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30062091/
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-10-28 11:36:29  来源:igfitidea点击:

Change H3 to H2 with jquery keeping href and html elemens

javascriptjqueryhtmlcss

提问by user2087563

I need to change (just) the h3tag to h2, keeping all default html elements inside, this code are erasing all html contents !!

我需要将h3标签(仅)更改为h2,将所有默认的 html 元素保留在里面,此代码正在擦除所有 html 内容!

<script type="text/javascript">
$(function () {
        $('.sideMenu h3').replaceWith(function () {
        return "<h2>" + $(this).text() + "</h2>";
    });
});
</script>

<div class="sideMenu">
    <h3 class="sapanos">
       <span></span>
       <a href="#" title="Sainos">Sapanos</a>
    </h3>
</div>

回答by Barmar

Use .html()to keep all the HTML structure. text()just gets the plain text, and throws away all the tags.

使用.html()保留所有的HTML结构。text()只获取纯文本,并丢弃所有标签。

$('.sideMenu h3').replaceWith(function () {
    return "<h2>" + $(this).html() + "</h2>";
});

To keep the classes, do:

要保留课程,请执行以下操作:

$('.sideMenu h3').replaceWith(function() {
    return $("<h2>", {
                "class", this.className,
                html: $(this).html();
            });
});


回答by Martin Carney

The problem is in

问题出在

return "<h2>" + $(this).text() + "</h2>";

Instead of .text(), use .html().

而不是.text(),使用.html()

.text()gets just the plain text content.

.text()只获取纯文本内容。

.html()gets the html content, which is what you want to transfer over.

.html()获取 html 内容,这是您要传输的内容。