How to use a jQuery variable in a selector
I'm trying to highlight the ta开发者_如何转开发ble cell that is in row, col.
var $tr = $('tr:eq(' + row + ')');
$($tr:nth-child(col)).addClass('highlight');
var $tr = $('tr:eq(' + row + ')');
$tr.find(':nth-child(' + col + ')').addClass('highlight');
Using .find()
. See demo.
Alternatively, if you don't need a reference to the $tr
, you can do it all via one selector:
$('tr:eq(' + row + ') :nth-child(' + col + ')').addClass('highlight');
(Demo)
As for your question
How to use a jQuery variable in a selector
The result of (all) jQuery traversal / selector methods is of type jQuery
. This makes it possible to do advanced chaining. Also, it is on this type that the jQuery methods is defined. This means that you need to perform filtering etc. on the resulting object. Thus, the following is invalid (:
is not a JavaScript operator, nth-child()
is (probably) not defined as a JavaScript function):
$($tr:nth-child(1)).addClass('highlight');
But can be rewritten as:
$tr.find(':nth-child(1)').addClass('highlight');
Here we're applying the selector :nth-child(1)
on the jQuery
object assigned to $tr
. This object can hold a reference to any number of DOM elements, even zero!
i'm guessing something like this?
<html>
<head>
<style>
.highlight{
color:red;
}
</style>
<script type="text/javascript" src="jquery-1.4.2.min.js" ></script>
<script type="text/javascript">
$(document).ready(function(){
var row = 1;
var col = 2;
$("tr:nth-child(" + row + ") > td:nth-child(" + col + ")").addClass('highlight');
});
</script>
</head>
<body>
<table>
<tr>
<td id="1">hello</td>
<td id="1">hello2</td>
</tr>
<tr>
<td id="2">world</td>
<td id="2">world2</td>
</tr>
</table>
</body>
</html>
You have to escape the first set of double quotes -- leave the single quotes there.
var row = "billy";
var $tr = $("tr:eq('" + row + "')");
$($tr:nth-child(col)).addClass('highlight');
精彩评论