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

标签 javascript jquery html

如何删除所有标签:table , tbody , tr来 self 的 HTML 代码?最后我想全部替换

<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);
}

关于javascript - 在 jQuery 中将所有 <td>content</td> 替换为 <li>content</li>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11874454/

相关文章:

HTML 默认链接颜色

javascript - 如何组合从不同的 JS 文件对 Ajax 数据库的多个调用

php - 如何将 id 从 jquery 方法传递到服务器端

javascript - 多日期选择器错误?

html - 只有div的背景被img隐藏了?

jQuery 交叉淡入淡出 2 个带有缩略图点击的图像

javascript - 与其他软件和程序相比,JavaScript 粒子性能背后的原因

javascript - 模数和余数 - Javascript

javascript - jQuery 最新库不工作脚本

javascript - 如何读取不同路径的cookie