1

我有一个 jquery 函数,它获取选中复选框的 td 的 id 值。我需要给那些 td 上色。我写了这个函数,它没有给我任何错误,但也不给 td 着色..

这是功能:

$('#custom-interval-tbl td').each(function() {
 $(this).find('input:checkbox:checked').each(function() {      
    var tdId= $(this).attr("id");
    var tdElement = $("#custom-interval-tbl td").eq(tdId); 
    console.log("TD Element"+tdElement);        
    tdElement.css({background:"#333333"});
    });
});

有人可以告诉我我在做什么错吗?

谢谢你的帮助。

4

2 回答 2

1

jsFiddle 演示

问题是您正在使用.eq()(它是基于索引的),但您给它的id是复选框。

附带说明,不要使用 :text / :checkbox / 等,这些在 jQuery 中已被弃用,最好使用 native[type="checkbox"]等。

$('#custom-interval-tbl td').each(function() {
    $(this).find('input[type="checkbox"]:checked').each(function() {
        // You don't need to find out ID or anything.
        // Just go up to the closest <td> and give it the background

        var tdElement = $(this).closest('td');     
        tdElement.css({ background : "#333333" });
    });
});​
于 2012-08-14T23:32:18.277 回答
1

我认为这里的问题是this第二个函数内部是指checkbox,而不是td。试试这个:

$('#custom-interval-tbl td').each(function() {
 $(this).find('input:checkbox:checked').each(function() {      
    var tdElement = $(this).parent("td");
    console.log("TD Element"+tdElement);        
    tdElement.css({background:"#333333"});
    });
});
于 2012-08-14T23:42:00.433 回答