开发者

Using a variable when traversing elements in JQuery

Very quick and hopefully simple question.

I am trying to select a hidden input by value with some pr开发者_StackOverflow社区edefined variable.

var id = $("#puid").val();
$('input[value=id]').closest('tr').css({'background-color':'red'});

I thought the above code would have worked, however its not processing id as a variable. What is the right notation to do this? (I have tested the code by replacing id with the actual number and the rest of the code works fine).


remove it from the quotes, so the variable is concatenated into the string. They way you have it, it's looking for the literal value "id", and has no way of knowing that you're talking about a variable.

$('input[value='+id+']')

edit: more info - you could put double quotes around the id part, inside the strings, as in Nick's answer, which would make it safe to use with non-numeric ids. I omitted them since your example doesn't need them, as you said your ids are numeric.


Concatenate the string selector with the variable, like this:

var id = $("#puid").val();
$('input[value="' + id + '"]').closest('tr').css({'background-color':'red'});

Currently, it's looking exactly for this: value="id", but you want your variable there.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜