gpt4 book ai didi

javascript - 如何应用 jQuery CSS 选择器

转载 作者:可可西里 更新时间:2023-11-01 13:02:23 25 4
gpt4 key购买 nike

我正在尝试在从 javaScript 循环动态创建的 div 上应用 jquery 选择器

div 是从 for 循环创建的,为每个 div 分配类

minus = textbox1 - textbox2;

var count = 0;
var a;
for (x = textbox1; x >= minus; x--) {
a = count++;
$('body').append('<div class="drag' + a + '" >' + x + '</div>');
}

现在我正尝试在这些上添加 css 选择器,但它不起作用

var colors = ["#42ae18","#eabc00","#147cc4","#FF6EB4","#ed4329","#8d33aa","#00b971","#e9681b","#a2b3d4","#0b863c","#eabc00","#7027a5","#c83131","#00a1de","#0bc1b6","#FF6EB4","#10a0b6","#FF6EB4","#eedfd3","#362819","#FFD700"];
var i = 0;
$(".drag").each(function(){
$(this).css("color",colors[i]);
if(i == colors.length-1)
{
i = 0;
}
else
{
i++;
}
});

完整代码如下

$("#submitBtn").click(function(){    
var x;
var minus;
var textbox1= new Number($("#value1").val());
var textbox2= new Number($("#value2").val());

var colors = ["#42ae18","#eabc00","#147cc4","#FF6EB4","#ed4329","#8d33aa","#00b971","#e9681b","#a2b3d4","#0b863c","#eabc00","#7027a5","#c83131","#00a1de","#0bc1b6","#FF6EB4","#10a0b6","#FF6EB4","#eedfd3","#362819","#FFD700"];
var i = 0;
$(".drag").each(function(){
$(this).css("color",colors[i]);
if(i == colors.length-1)
{
i = 0;
}
else
{
i++;
}
});

minus=textbox1-textbox2;

var count=0;
var a;
for(x=textbox1;x>=minus;x--){
a=count++;
$('body').append('<div class="drag'+a+'" >' +x+ '</div>');
}
});

最佳答案

您可以使用 attribute starts with selector喜欢以下。

var colors = ["#42ae18", "#eabc00", "#147cc4", "#FF6EB4", "#ed4329", "#8d33aa", "#00b971", "#e9681b", "#a2b3d4", "#0b863c", "#eabc00", "#7027a5", "#c83131", "#00a1de", "#0bc1b6", "#FF6EB4", "#10a0b6", "#FF6EB4", "#eedfd3", "#362819", "#FFD700"];
var i = 0;
$("[class^=drag]").each(function () { //change selector here
$(this).css("color", colors[i]);
if (i == colors.length - 1) {
i = 0;
}
else {
i++;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="drag0">!!!!!</div>
<div class="drag1">!!!!!</div>
<div class="drag2">!!!!!</div>
<div class="drag3">!!!!!</div>
<div class="drag4">!!!!!</div>
<div class="drag5">!!!!!</div>
<div class="drag6">!!!!!</div>
<div class="drag7">!!!!!</div>
<div class="drag8">!!!!!</div>

关于javascript - 如何应用 jQuery CSS 选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37420355/

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