【问题标题】:JQuery .replaceWith() html element to div classJQuery .replaceWith() html 元素到 div 类
【发布时间】:2015-07-30 05:08:27
【问题描述】:

我想换

<div class="blog">Blog</h1>

与

<h1>Blog</h1>

在类名“sidebar”中

我使用了这段代码但没有用:

$(window).load(function() {
    $( ".sidebar h1" ).replaceWith( "<div class="blog">Blog</h1>" );
}

我的代码有什么问题?

【问题讨论】:

    标签: jquery replacewith


    【解决方案1】:

    如果要在由双引号分隔的字符串中使用双引号,则必须使用反斜杠对其进行转义:

    "<div class=\"blog\">Blog</h1>"
    

    许多程序员对 JavaScript 字符串使用单引号,这使得在嵌入的 HTML 中使用双引号更容易。

    还要注意标签应该用匹配的标签关闭。而不是

    '<div class="blog">Blog</h1>'
    

    ……这样做:

    '<div class="blog">Blog</div>'
    

    这里有一个解决方案:

    $('.sidebar h1').replaceWith('&lt;div class="blog"&gt;Blog&lt;/div&gt;');
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="sidebar">
      <h1>Blog</h1>
    </div>

    【讨论】:

      【解决方案2】:

      首先,您打开一个 div 标签并关闭一个 h1 标签。

      其次,您的引号在 .replaceWith 位中不匹配。

      我会这样做:

      <h1 id="replaceme">Blog</h1>
      <script>
      $(window).load(function() {
          $("#replaceme").replaceWith('<div class="blog">Blog</div>');
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-10-13
        • 2011-12-13
        • 1970-01-01
        • 1970-01-01
        • 2012-09-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多