jQuery nth-child selector
Got a small confusing issue with jQuery and selecting/styling a column in a table.
The following code works:
$(function() {
$("table").delegate('th.selcol','click', function(e) {
var iCol = $(this).parent().children().index(this)+1;
$("table tr td:nth-child(10)").each(function () {
$(this).toggleClass("colhighl开发者_JAVA百科ight");
});
});
});
But this code, changing the nth-child(10) to nth-child(iCol) produces an error "uncaught exception: Syntax error, unrecognized expression: :nth-child"
$(function() {
$("table").delegate('th.selcol','click', function(e) {
var iCol = $(this).parent().children().index(this)+1;
$("table tr td:nth-child(iCol)").each(function () {
$(this).toggleClass("colhighlight");
});
});
});
Any help would be greatly appreciated.
$("table tr td:nth-child(" + iCol + ")").each(function () {
$(this).toggleClass("colhighlight");
});
nth-child expects an integer, not a string, so you can use concatenation to solve your problem.
Try this:
"table tr td:nth-child("+iCol+")"
Change it into this:
$(function() {
$("table").delegate('th.selcol','click', function(e) {
var iCol = $(this).parent().children().index(this)+1;
$("table tr td:nth-child(" + iCol + ")").each(function () {
$(this).toggleClass("colhighlight");
});
});
});
try this:
$(function() {
$("table").delegate('th.selcol','click', function(e) {
var iCol = $(this).parent().children().index(this)+1;
$("table tr td:nth-child("+iCol+")").each(function () {
$(this).toggleClass("colhighlight");
});
});
});
Hope it works :)
精彩评论