jQuery-为什么在我的代码中:first和:last有效,但:nth-​​child2不起作用?

问题描述

| 请考虑以下html代码段及其与jQuery 1.3.2版相对应的代码:
<tr>
    <td>id</td>
    <td><input type=\'checkbox\' /></td>
    <td><input type=\'checkbox\' /></td>
    <td><input type=\'checkbox\' /></td>
    <td><select>
    <option value=\'0\'>0</option>
    <option value=\'1\'>1</option>
    <option value=\'2\'>2</option>
    <option value=\'3\'>3</option>
    <option value=\'4\'>4</option>
    <option value=\'5\'>5</option>
</select></td>
</tr>
jQuery函数:
function submitRoutesForm()
{
    data = new Array();
    $(\'#routes_table option:selected\').each(function()
    {
        qty = $(this).val();
        if( qty != 0)
        {
            tmp = new Array();
            tr = $(this).closest(\'tr\');
            tmp[\'route_id\'] = tr.find(\'td:first\').html();
            tmp[\'qty\'] = qty;
            tmp[\'isChild\'] = $(tr).find(\'td input:first\').is(\':checked\');
            tmp[\'isInvalid\'] = $(tr).find(\'td input:nth-child(2)\').is(\':checked\');
            tmp[\'isSpecialDiet\'] = $(tr).find(\'td input:last\').is(\':checked\');
            data.push(tmp);
            console.log(tmp);
        }
    });

return false;
} 我可以确认一切正常,期望第二个复选框的结果始终返回\“ false \”。似乎我的选择器:nth-​​child(2)由于某种原因无法正常工作... 预先非常感谢,我坚持了一段时间:(     

解决方法

第n个孩子将寻找td元素的一个孩子,每个孩子只有一个孩子。您应该在td上使用:eq(2)。这将为您提供匹配结果集的索引,而不是某个子项。
$(tr).find(\'td input:eq(2)\').is(\':checked\');
    ,您没有a3ѭ,而
input
不止一个,因此
nth-child(2)
将找不到任何东西。     

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...