gpt4 book ai didi

使用 CSS 转义的具有数字 id 的元素的 jQuery 选择器

转载 作者:太空狗 更新时间:2023-10-29 12:33:37 24 4
gpt4 key购买 nike

我正在尝试使用 jQuery(i 等于 1)为 div id='1' class='std' 赋予红色:

$("#" + i).css("background-color", "red");

代码片段:

           for(var i=0 ; i< info.length ; i++ ){

var div_std ='<div id="'+i+'" class="std"> <p> Name :<b> '+info[i].nom_etud + ' </b></p> <hr><p> Abs Hours : '+info[i].hr_cours +'</p>' ;
div_std+='<p> TPs Hours : '+info[i].hr_tp+'</p><section id="footstd"><button type="button" name="">Mark as absent</button><img src="images/abs.png"></section>'+'</div>';

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 escapes :

$(function() {
// #1 should be escaped as #\31
$("#\\31").css("background", "red");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="1">div</div>

这是一个较长的 id 1 ... 100 示例:

$(function() {
var i, selector, $div;
for (i = 1; i <= 100; i++) {
selector = "#\\" + i.toString().charCodeAt(0).toString(16) + " " + i.toString().substr(1);
$div = $('<div id="' + i + '"><code>id: ' + i + ', selector: ' + selector + '</code></div>').appendTo("body");
$(selector).css("background", "green");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

话虽如此,在您的情况下,您可以简单地使用内联样式来更改背景颜色,而不是使用 CSS 选择器:

var bgcolor = ["red", "blue", "green"][info[i].col - 1] || "transparent";
var div_std = '<div id="' + i + '" class="std" style="background-color: ' + bgcolor + '">...'

关于使用 CSS 转义的具有数字 id 的元素的 jQuery 选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29327060/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com