jQuery忽略返回集合中的最后一个元素

时间:2014-05-31 12:29:16

标签: jquery html jquery-datatables

我正在研究jQuery dataTables的内部插件,我遇到了奇怪的行为。

看一下以下小提琴:http://jsfiddle.net/bJLLz/

下面的代码是查找每个'tr'第一个'td'元素,并在找到的每个匹配项之前添加另一个带有复选框输入的'td'。 (注意上面小提琴中的最后一行没有复选​​框)

$(function () {
    var checkBox = $('<input>', {
        "type": "checkbox"
    })
    var td = $('<td/>', {
        'class': "table-checkbox"
    }).insertBefore("tbody > tr > td:first-child")

    var checkBoxes = $(checkBox).appendTo(td)
    var th = $('<th/>', {
        'class': 'text-center'
    }).insertBefore("thead > tr:nth(0) > th:nth(0)")

    $(checkBox).appendTo(th)
        .change(function () {
        $(this).is(":checked") ? checkBoxes.prop('checked', true) : checkBoxes.prop('checked', false);
    })
})

虽然jQuery添加了相关的'td'元素,但是添加了表中的最后一个'td',但是没有复选框输入..

这真是出乎意料..有没有人知道为什么?

2 个答案:

答案 0 :(得分:1)

这一行是这样的:

$(checkBox).appendTo(th)

.insertBefore()不同,.appendTo() 元素移动到新位置。在该行checkBox之前的所有其他操作引用表的最后一行的复选框之后。

在添加复选框之前,您需要复制该复选框:

$(checkBox).clone().appendTo(th)

Demo

答案 1 :(得分:1)

Juhana对你的问题是完全正确的,但我看到了一个修复它的机会。我简化了你的代码并使用了一些事件委托来处理change事件。

$(function () {

    $('table').on('change', '.row-checkbox', function () {
        $(this).closest('tr').toggleClass('highlighted', this.checked);
    });

    $('table tr').each(function(){
        $(this).find('td,th').first().before(function () {
          return '<td><input type="checkbox" class="row-checkbox"></td>';
        });
    });

});

以下是演示:http://jsfiddle.net/bJLLz/2/