使用jQuery用表列替换span元素

时间:2014-01-22 16:06:10

标签: javascript jquery html

我有包含列和<span>元素的表格,我想用&lt; td>列替换span元素:

<td>
    <span>Chestnut Suede Boot</span>
    <br>
    <br>
    <span>867008</span>
    <br>
    <br>
    <span>8 eu 25.5</span>
    <br>
    <br>
    <span>1</span>
    <br>
    <br>
    <span>10.00</span>
</td>

看起来像:

<td>
    <td>Chestnut Suede Boot</td>
    <br>
    <br>
    <td>867008</td>
    <br>
    <br>
    <td>8 eu 25.5</td>
    <br>
    <br>
    <td>1</td>
    <br>
    <br>
    <td>10.00</td>
</td>

我尝试了以下jQuery命令:

$('<td>').replaceAll('<span>');

但它不起作用,如果我做以下它似乎工作,它用跨度替换td:

$('<span>').replaceAll('<td>');

替代方案我尝试将<br>转换为列:

$('br').replaceAll('</td><td>');

以便第一个</td>关闭顶部<td>,依此类推,以便我拥有:

<td><span>Description</span></td>
<td></td>
<td><span>Item</span></td>
<td></td>
<td><span>Size</span></td>
<td></td>
<td><span>Qty</span></td>
<td></td>
<td><span>Price</span></td>

问题在于它将<br>替换为<td></td>而不是</td><td>,这会导致错误。

请帮忙吗?

3 个答案:

答案 0 :(得分:1)

要使用jQuery替换标记,您可以使用replaceWith,将函数作为参数传递。

$('span').replaceWith(function(){
    return $("<td />", {html: $(this).html()});
});

但在您的代码中,我不明白为什么您希望另一个td中有td

答案 1 :(得分:0)

这是一种做法

$('span').each(function() { 
     $(this).replaceWith($('<td'>+this.html()+'</td>')); 
});

由于td中的td不起作用,因此最好通过删除<br>将HTML转换为符合语义的代码。通过$('td br').remove();

<td>
  <div>
    <span>Chestnut Suede Boot</span>
    <span>867008</span>
    <span>8 eu 25.5</span>
    <span>1</span>
    <span>10.00</span>
  </div>
</td>

然后使用CSS以您想要的方式对齐它。为此,您可以使用例如

td > div { display: table-row; }
td > div > span { display: table-cell; }

答案 2 :(得分:0)

我不完全确定嵌套td是否是有效的html,但是下面的代码可以帮助你。

$('table tbody tr td span').replaceWith(function () {
    return '<td>' + this.innerHTML + '</td>';
});

http://jsfiddle.net/xW77R/