在jQuery中将所有<td>content</td>替换为<li>content</li>

replace all <td>content</td> with <li>content</li> in jQuery

本文关键字:li content td 替换 jQuery      更新时间:2023-09-26

如何从我的HTML代码中删除所有标签:tabletbodytr?最后我想填满所有

<td>
    <input id="selectOne" type="radio" value="1" name="selectOneRadio">   
</td>

<li>
    <input id="selectOne" type="radio" value="1" name="selectOneRadio"> 
</li> 

我需要一个jQuery函数。请帮我:)

<table>
    <tbody>
        <tr>
            <td>
                <input id="selectOne" type="radio" value="1" name="selectOneRadio">
                <label for="selectOne">
            </td>  
       </tr>    
    </tbody>
</table>

从评论...

label元素应保留。我尝试过:

$('table td').each(function () {
    $(this).replaceWith(function () {
        return $('<li>' + this.innerHTML + '</li>')
    })
});

然后

jQuery.fn.unwrap = function (el) {
    return this.each(function () {
        $(this.childNodes).appendTo(this.parentNode);
    });
};
$('tr, table, tbody').unwrap().remove();

但它对我不起作用。

创建一个包含 document.createElement 的列表。然后遍历表的rows[]数组,对于每个数组,获取cells[]数组并执行您需要的操作,以便将其放入列表项中(可能document.createElement创建列表项,然后将单元格的innerHTML复制到其中)。

完成后,使用 insertBefore 将列表放在表所在的位置,最后使用 removeChild 删除表。


上述实施:

function replaceTableWithList(tableid) {
    var table = document.getElementById(tableid),
        rows = table.rows, cells, list = document.createElement('ul'),
        len = rows.length, i, item;
    for( i=0; i<len, i++) {
        item = list.appendChild(document.createElement('li'));
        cells = rows[i].cells;
        while(cells[0].firstChild) item.appendChild(cells[0].firstChild);
        // this only gets the contents of the first cell in a row
        // to get the whole row will need another loop
    }
    table.parentNode.replaceChild(list,table);
}

我会使用解包/包装功能:

$('table').contents().unwrap(); $('tr').contents().unwrap(); $('td').contents().unwrap().wrap('<li/>');

我会把你的桌子包装在某种容器中:

<div id="content">
    <table>
        <tbody>
            <tr>
                <td>
                    <input type="radio" />
                </td>
            </tr>
            <tr>
                <td>
                    <input type="radio" />
                </td>
            </tr>
            <tr>
                <td>
                    <input type="radio" />
                </td>
            </tr>
        </tbody>
    </table>
</div>​​​​

然后使用 jQuery 并执行以下操作:

// Hide the table
$('#content table').hide();
// Append a ul to the content div
$('<ul />').appendTo('#content');
// For each td, wrap children in an li and append to the ul​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
$('#content table td').each(function (index, element) {
    $(element).children().appendTo('#content ul').wrap('<li />');
});