2014-11-22 72 views
0

如果我的表看起来像这样在HTML在.filter函数()不工作,因为我想

<table> 
    <tr> 
     <td>foo 
     <td>bar 
     <td>alpha 
     <td>beta 
     <td>seta 

    </tr> 
    <tr> 
     <td>foo1 
     <td>bar2 
     <td>alpha3 
     <td>beta3 
     <td>seta3 
    </tr> 
</table> 

,我是刚刚通过的jQuery去格式化的表格。

//this one perfectly works 
//this turns even columns into red!! 
$("td").filter(':odd').addClass('colorRedClass'); 

但我想用同样的功能!可能吗?

//i returned the value ':odd' from the function!! 
//this turns every column into red!! 
//this is not working as expected!! 
$("td").filter(function(){ 
     return ':odd'; 
    }).addClass('colorRedClass'); 

而colorRedClass在CSS中有属性color:red;

所以,我的问题是,为什么不能第二个工作?为什么第二个人只是将列变成红色?我来自c,C++,java背景,根据我的理解,如果我在这些语言中采用相同的方式,返回应该可以工作。

我错过了什么?

+0

你真的应该关闭''​​。它不是有效的HTML,并且让浏览器猜测它关闭的位置,从而导致可能不需要的行为。 – Bigood 2014-11-22 14:49:04

+0

@Bigood:这个_is_在HTML 4.01和HTML5中是有效的。 – CBroe 2014-11-22 14:53:10

+0

@CBroe不知道这个,忘了我的评论。 [这里是关于像我这样的无知的W3的参考](http://www.w3.org/TR/html401/struct/tables.html#h-11.2.6) – Bigood 2014-11-22 14:57:39

回答

3

传递给过滤器的功能应该有类型:

Type: Function(Integer index, Element element) => Boolean 

因此,期望你如果该元素将被包含在过滤的,而不是使用选择返回true。

你可以使用索引参数来决定该元素是否是奇数:

$("td").filter(function(index){ 
    var isOdd = index % 2 === 1; 
    return isOdd; 
}).addClass('colorRedClass'); 
相关问题