admin管理员组

文章数量:1405170

I am trying to pass in a variable as an index to set an active row with a little bit of jquery. I have my variable storing correctly but cannot seem to get jquery to accept the variable in an argument.

Here's what I've got:

$(this).find("td:eq('storeDex')").addClass("activeRow");

storeDex is the variable, If I drop a normal number there it seems to work fine, I'm thinking maybe I need to escape the vaiable some how but I cannot seem to figure out how to do it. Any help would be much appreciated. Thanks!

I am trying to pass in a variable as an index to set an active row with a little bit of jquery. I have my variable storing correctly but cannot seem to get jquery to accept the variable in an argument.

Here's what I've got:

$(this).find("td:eq('storeDex')").addClass("activeRow");

storeDex is the variable, If I drop a normal number there it seems to work fine, I'm thinking maybe I need to escape the vaiable some how but I cannot seem to figure out how to do it. Any help would be much appreciated. Thanks!

Share Improve this question asked Oct 2, 2014 at 21:36 ajmajmajmaajmajmajma 14.2k25 gold badges83 silver badges138 bronze badges 1
  • OK, I finally got my snippet working in my answer below. Basically like you said, you have to escape the variable, but it's not called escaping, it would actually be concatenation of the jQuery selector string to include your variable as a literal in the string. – Zack Commented Oct 2, 2014 at 21:55
Add a ment  | 

2 Answers 2

Reset to default 8

From the jQuery :eq selector documentation http://api.jquery./eq-selector/

$( "td:eq( 2 )" ).css( "color", "red" );

So I would leave out the single quotes in your example, and the result would look like this:

$(this).find("td:eq(" + storeDex + ")").addClass("activeRow");

Snippet example

var storeDex = 2;
$(function () {
    $("td:eq(" + storeDex + ")").addClass("activeRow");
});
.activeRow {
  background-color:yellow;
}
<script src="https://ajax.googleapis./ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<table>
  <tr>
    <td>Table cell 1</td>
    <td>Table cell 2</td>
    <td>Table cell 3</td>
    <td>Table cell 4</td>
  </tr>
</table>

You need to terminate your string, append the variable and finish your jquery selector with another string.

$(this).find("td:eq('" + storeDex + "')").addClass("activeRow");

本文标签: javascriptEscape a variable in jqueryStack Overflow