繁体   English   中英

如何使用jQuery替换HTML标签

[英]How to replace html tags using jquery

我想使用Java脚本将div和span标签更改为tr td。 但是,Java脚本替换功能仅替换第一次出现的内容,而保持原样。

<div style="width:100%">
  <div style="border-bottom:1px solid #DDDDDD; padding:10px 0px; height:100%; overflow:hidden;">
    <span style="width:420px; display:block; float:left; border-bottom:1px thin #333333;background:#F2F2F2">
      Custom Stirrups : Category - Adult ,Size-One size fits most 
    </span> 
    <span style="width:220px; display:block; float:left; border-bottom:1px thin #333333;background:#F2F2F2">
      NO
    </span>
    <span style="width:140px; display:block; float:left; border-bottom:1px thin #333333;background:#F2F2F2">
      1
    </span><br />
  </div>
  <div style="border-bottom:1px solid #DDDDDD; padding:10px 0px; height:100%; overflow:hidden;"> 
    <span style="width:420px; display:block; float:left; border-bottom:1px thin #333333;background:#F2F2F2">
      Flat Visor Fitted : Fitted Sizes - 7 1/8 
    </span> 
    <span style="width:220px; display:block; float:left; border-bottom:1px thin #333333;background:#F2F2F2">
      NO 
    </span> 
    <span style="width:140px; display:block; float:left; border-bottom:1px thin #333333;background:#F2F2F2">
      1
    </span>
    <br />
  </div>
</div>

我想要类似的东西

<table width="100%">
        <tbody>
          <tr>
            <td width="471" style="background:#F2F2F2">Cap : Fitted Sizes - 6 5/8 </td>
            <td width="240" style="background:#F2F2F2">YES</td>
            <td width="145" style="background:#F2F2F2">1</td>
          </tr>
          <tr>
            <td width="471" style="background:#F2F2F2">Grey Dri-fit Undershirt : Size - XXL </td>
            <td width="240" style="background:#F2F2F2">YES</td>
            <td width="145" style="background:#F2F2F2">1</td>
          </tr>
         </tbody>
      </table>

这是我正在尝试的脚本...请让我知道我错了

var data = $('#dvData').html();
  data = data.replace('/<div style="width:100%">/g', '<table width="100%"><tbody><tr>');
  data = data.replace('/</div>/g', '</tbody></table></tr>');

提前致谢..

请参阅http://www.w3schools.com/jsref/jsref_replace.asp。这是用于全局替换的:

var str="Mr Blue has a blue house and a blue car";
var n=str.replace(/blue/g,"red");

那里也提供了其他示例。

我看到您也标记了jquery,所以假设您也接受jquery?

您可以为此使用.replaceWith()

$('span, div, tr , td').replaceWith('Replaced!');

好吧,当dom被解析时,它是不变/不变的

您可以尝试以下方法:

$('div').contents().unwrap().wrap('<tr/>');

看那里的tr标签...

如果它有作用的尝试

$(this).replaceWith($('<tr>' + this.innerHTML + '</tr>'));

您可以尝试类似的方法。.我知道这不是最好的方法...

var data = $('#dvData').html();
  data = data.toString();
    data = data.replace('<div style="width:100%">', '<table width="100%">');
data = data.replace('span', 'td');

因此,请尝试使用.replaceAll()。 如果没有帮助,请使用循环。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM