开发者

Jquery [name=var] substitution

Is there a way to use a variable in the name= paramet开发者_JAVA技巧er.

I would like to be able to do:

var a = 1;

$("#gen_p").html($("input:radio[name='gen'+a]:checked").val()));

I am able to do $("#gen_p"+a) but not in the [name=??]

Have I missed something?

Thanks


$("#gen_p").html($("input:radio[name='gen"+a+"']:checked").val());​​

You're mixing some single quotes in there.

EDIT: You were also having some extra ) in there.


Yes, you can do that, but you put single quotes within the double quotes, so it's reading it literally as "'gen'+a", not "gen" + a.

Try this:

$("#gen_p").html($("input:radio[name=gen" + a + "]:checked").val()));


You are missing double quotes as well as + operator there:

var a = 1;
$("#gen_p").html($("input:radio[name='gen'" + a + "]:checked").val()));

In javascript, variables should not come inside single/double quotes, rather they should be put outside of them and separated with + operator (which is also concatenation operator in javascript).


When quotes get messy, I prefer using string replace.

var selector = "input:radio[name='gen{a}']:checked".replace("{a}", a);

$("#gen_p").html($(selector).val());
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜