【问题标题】:Replace <A> tag with <DIV> using jQuery使用 jQuery 将 <A> 标记替换为 <DIV>
【发布时间】:2013-05-02 14:06:08
【问题描述】:

我有以下代码:

<div class="normal">
    <div>
        <div>~Content 1~</div>
    </div>
</div>

<div class="normal replace">
    <a href="#">
        <div>~Content 2~</div>
    </a>
</div>

使用 jQuery,我想用普通的 &lt;div&gt; 标签替换 &lt;div class="normal replace"&gt; 中的 &lt;a&gt; 标签,同时保留它的内容。

<div class="normal replace">
    <div="result">
        <div>~Content 2~</div>
    </div>
</div>

【问题讨论】:

  • 这个问题肯定有很多重复...
  • 请以正确的格式书写
    。我想你忘了提到 id 或 class。
  • @vinothini 这显然是一个例子,这真的重要吗! ;-)
  • @Zenith 不幸的是,只有更改 div 内容的解决方案,而不是在保留其内容的同时替换 div。

标签: jquery html replace


【解决方案1】:

请点击下面我为您尝试的 jsfiddle 示例。

@987654321@

希望对您有所帮助。

【讨论】:

    【解决方案2】:

    试试这样的:

    // Select the 'a' tag to be replaced and call the replaceWith method
    $('.normal a').replaceWith(function(){
        // Execute a callback to generate contents of the replacement
        // The $('<div>') part creates a div
        return $('<div>', {
            html: this.innerHTML // This takes the html of the 'a' tag and copies it to the new div
        });
    });
    

    jQuery replaceWith 方法获取项目并将其替换为回调函数返回的内容。

    更多信息请参见here

    【讨论】:

    • 返回应该是return $('&lt;div&gt;还是return $('&lt;div/&gt;'
    【解决方案3】:

    使用以下 $('div.normal.replace a').replaceWith( "" + $('div.normal.replace a').html() + "" );

    【讨论】:

      【解决方案4】:

      试试这个 -

      $('div.normal.replace a').find('div').unwrap().wrap("<div id='result'/>");
      

      【讨论】:

        【解决方案5】:

        你去这里原来是Using jQuery to replace one tag with another

        $('div.normal a').contents().unwrap().wrap('<div id='result'/>');
        

        【讨论】:

          【解决方案6】:
          $('.normal > a').replaceWith(function() {
              return $('<div/>', {
                  html: this.innerHTML
              });
          });
          

          http://jsfiddle.net/VMxAL/

          【讨论】:

          • 您返回的究竟是什么?我不明白你返回的结构。
          猜你喜欢
          相关资源
          最近更新 更多
          热门标签