javascript - Escape a variable in jquery - Stack Overflow

I am trying to pass in a variable as an index to set an active row with a little bit of jquery. I have

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");

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744247284a4564996.html

相关推荐

  • javascript - Escape a variable in jquery - Stack Overflow

    I am trying to pass in a variable as an index to set an active row with a little bit of jquery. I have

    9天前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信