我在页脚中有一个表格单元格,允许用户打开行着色: $('#highlight').click(function() {$(this).parents('table').RowColors();})// From Chapter 7 of Learning jQuery$.fn.RowColors = function() {$('tbody tr:odd', this).removeC
$('#highlight').click(function() {
$(this).parents('table').RowColors();
})
// From Chapter 7 of Learning jQuery
$.fn.RowColors = function() {
$('tbody tr:odd', this).removeClass('even').addClass('odd');
$('tbody tr:even', this).removeClass('odd').addClass('even');
return this;
};
问:如何编写一个选择器:如果至少有一行class =“even”,则删除“even”和“odd”ELSE执行RowColors函数.
我的建议是略有不同.只有一个类的默认状态是另一个.所以:tr td { background: yellow; }
tr.odd td { background: blue; }
然后这很简单:
$("tr").toggleClass("odd");
或者更具体地说:
$("tbody > tr").removeClass("odd").filter(":nth-child(odd)").addClass("odd");
注意:避免使用:odd和:even.它们通常并不代表您认为的含义. :nth-child(单数)和:nth-child(even)往往是你真正的意思.
我可能会写一些类似的东西:
$("#highlight").click(function() {
$(this).closest("table").children("tbody").children("tr").removeClass("odd")
.filter(":nth-child(odd)").addClass("odd");
return false;
});
如果您愿意,可将其放入单独的功能中.
编辑:检查是否有空:
var odd = $(".odd");
if (odd.length == 0) {
// do one thing
} else {
// do something else
}
jQuery对象支持length属性和size()方法,它们执行相同的操作.
