使用CSS转义的带有数字id的元素的jQuery选择器
我试图使用jQuery(i等于1)给div id =’1’class =’std’一个红色:
$("#" + i).css("background-color", "red");
代码段:
for(var i=0 ; i< info.length ; i++ ){ var div_std =' Name : '+info[i].nom_etud + '
Abs Hours : '+info[i].hr_cours +'
' ; div_std+=' TPs Hours : '+info[i].hr_tp+'
'+''; if(info[i].col == 1) { $(function() { $("#\\" + i.toString().charCodeAt(0).toString(16)).css("background", "red"); }); } else if(info[i].col == 2) $(function() { $("#\\" + i.toString().charCodeAt(0).toString(16)).css("background", "blue"); }); else if(info[i].col == 3) $(function() { $("#\\" + i.toString().charCodeAt(0).toString(16)).css("background", "green"); }); $(".main").append(div_std); //Display the students name }
要匹配以数字或特殊字符开头的ID,您应该使用CSS转义 :
$(function() { // #1 should be escaped as #\31 $("#\\31").css("background", "red"); });
div
正如@ D4V1D所说,通过CSS访问#1
是不可能的,但是使用jQuery你甚至可以采用平面方式,而不需要div[id=x]
。 看到:
var i = 1; $('#' + i).css('background-color', 'red');
试试自己: http : //jsfiddle.net/wn7njfuc/
如果解决方案不适合您,可能您的jQuery无法无缝启动。
编辑1
根据OP的评论,他正在使用Jade。 所以,在你的div之前尝试这个:
script. $(document).ready(function () { var i = 1; $('#' + i).css('background-color', 'blue'); });
ID
不能以CSS
选择器的数字开头。
以下是您需要做的事情:
jQuery(function($) { $('div[id='+i+']').css("background-color", "red"); });
编辑
我的不好, #1
在CSS
不起作用,但在jQuery
起作用( 根据@ GuilhermeOderdenge的回答 )。 因此,不需要使用$('div[id=1]')
。