[英]Concatenate within a jquery variable
How can I use a variable inside jquery id selector? 如何在jquery id选择器中使用变量?
function more_comments(x){
var datalist = "#s" + x;
$('datalist li:hidden').slice(0, 2).show();
}
I've tried this 我已经试过了
var datalist = "s" + x;
$('#datalist li:hidden').slice(0, 2).show();
and this. 和这个。
$('#s' + x li:hidden').slice(0, 2).show();
If i manually write 如果我手动写
$('#s50 li:hidden').slice(0, 2).show();
and click on the tag with an id == s50, it works perfectly. 然后点击ID == s50的代码,即可正常运行。 I searched for the correct syntax and can't find it. 我搜索了正确的语法,但找不到它。 Thanks for any help. 谢谢你的帮助。
Have you tried like this? 你有这样尝试过吗?
var x = 's50';
$('#' + x + ' li:hidden').slice(0, 2).show();
If you want to concatenate a variable and a string, the variable needs to be outside of any '
or "
: 如果要连接变量和字符串,则变量必须在任何'
或"
:
function more_comments(x){
var datalist = "#s" + x;
$(datalist + ' li:hidden').slice(0, 2).show();
}
Using a template string (not supported by IE), you could use 使用模板字符串(IE不支持),您可以使用
$(`#s${x} li:hidden`).slice(0, 2).show();
And to avoid the variable creation beforehand 并避免事先创建变量
function more_comments(x){
$('#s' + x + ' li:hidden').slice(0, 2).show();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.