jQuery按索引选择多个表列

时间:2012-02-24 16:10:02

标签: javascript jquery

我已经看到某些相似的问题,但不完全一样,我对这个问题感到难过。

我要做的是创建一个小部件,它接受一个表,然后遍历表的td元素并设置一个游标:指针(现在)给它们,但只有我允许的那些。

这是我的代码的外观:

selectableGrid: function (options) {
            var indexes = options.columns // this is [1,2];

            return this.each(function () {
                // Make the td's in the grid selectable
                $(this).find("tbody td").attr("style", "cursor:pointer");
            });
        }

我想要实现的最终结果是什么?

<tbody>
   <td>hello</td> // index 0
   <td style="cursor:pointer">hello</td> //index 1
   <td style="cursor:pointer">hello</td> // index 2
</tbody>

请记住,我可以通过我的数组列表中的1,3发送,因此lt和gt不适用于我的场景(据我所知,无论如何)。

编辑: 为了达到这个目的,我使用了以下代码:

$(this).find("tr").each(function () {
         $(this).find("td").each(function (i, el) {
                if (indexes.indexOf(i) > -1) {
                    $(this).css("cursor", "pointer");
                };
         });
});

出于某种原因,“tbody td”不适用于单个循环,因为它只引用了标记的第一次迭代。

再次感谢Stack Overflow。

3 个答案:

答案 0 :(得分:2)

循环遍历td元素,并检查它们的兄弟姐妹的索引是options.columns数组中包含的索引。

selectableGrid: function (options) {
    var indexes = options.columns // this is [1,2];
    return this.each(function () {
        $(this).find("tbody td").each(function(){
            var columnIndex = $(this).index();
            if($.inArray(columnIndex, options.columns) != -1){
               $(this).css("cursor", "pointer");
            }
        });
    });
}

答案 1 :(得分:1)

遍历索引并使用http://api.jquery.com/eq/查找特定的td。

答案 2 :(得分:1)

.each会在代码中引用index参数.....:

var indexes = options.columns;
this.find("tbody td").each(function(i, el) {
    if ($.inArray(i,indexes)>-1) { // good idea, ggreiner
        $(this).css("cursor","pointer");
    };
});