2

我想使用 jQuery 在 HTML 表格的每一行中的第一个单元格的内容之前插入一个复选框。我尝试了以下方法:

$("table td:first-child").each(function() {
    $(this).append('<input type="checkbox" class="basic-kpi-row"/>');
});

这几乎可以工作,它将复选框插入正确的单元格,但复选框出现在内容之后而不是之前。

4

5 回答 5

2

append()添加到最后。您想要prepend(),它将在任何现有内容之前添加您的新元素。

于 2013-08-22T12:04:44.643 回答
1

你需要我们prepend而不是也,这里append不需要使用.each()

$("table td:first-child").prepend('<input type="checkbox" class="basic-kpi-row"/>');

演示:小提琴

于 2013-08-22T12:09:57.543 回答
1
$("table td:first-child").each(function() {
    $(this).prepend('<input type="checkbox" class="basic-kpi-row"/>');
});

参考前置

于 2013-08-22T12:05:10.513 回答
1
$("table td:first-child").each(function() {
    $(this).prepend('<input type="checkbox" class="basic-kpi-row"/>');
});

JS 小提琴链接

于 2013-08-22T12:06:53.153 回答
0

您需要使用 prepend 而不是 append 因为 append 将在末尾添加元素,而 prepend 将在 td 中的所有其他元素之前添加元素

也不需要使用每个,您可以使用以下内容:

$("table td:first-child").prepend('<input type="checkbox" class="basic-kpi-row"/>');
于 2013-08-22T12:30:31.037 回答