【问题标题】:Change H3 to H2 with jquery keeping href and html elemens [duplicate]使用jquery保留href和html元素将H3更改为H2 [重复]
【发布时间】:2015-07-15 17:24:32
【问题描述】:

我需要将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>

【问题讨论】:

  • 你试过"&lt;h2&gt;" + $(this).text() + "&lt;/h2&gt;"吗?

标签: javascript jquery html css


【解决方案1】:

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

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

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

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

【讨论】:

  • 现在我需要将 h2 更改为 h3,保留 h2 类和 html 元素。例如。

    html 元素

    html 元素

    TNKS !!!!!!!
  • 完全一样,只是互换标签。有什么问题?
  • 我的系统正在自动创建 h2 类,我没有手动访问这个 html 类的权限。例如:

    类不同...
  • 哦,你是问改变元素类型时如何保留类?
  • 查看更新后的答案。
【解决方案2】:

问题出在

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-13
    • 2016-06-17
    • 2021-08-09
    • 1970-01-01
    • 2022-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-15
    相关资源
    最近更新 更多