如何删除所有标签: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/