[英]Trying to make selector dynamic with javascript/jquery
Hello stackoverflow: I am trying to make the $('.TextBoxColors-')
part of my code dynamic.您好 stackoverflow:我正在尝试使我的代码中的$('.TextBoxColors-')
部分动态化。
I am looking for the i
variable in the for-loop to assign this value depending on the if
.我正在寻找 for 循环中的i
变量,以根据if
分配此值。
I have tried many things like $('.TextBoxColors-${i}')
, $('.TextBoxColors-').value(i)
as in $('.TextBoxColors-').value(i).css('background-color', 'green')
,我已经尝试了很多东西,比如$('.TextBoxColors-${i}')
, $('.TextBoxColors-').value(i)
就像在$('.TextBoxColors-').value(i).css('background-color', 'green')
,
but nothing works so far.但到目前为止没有任何效果。
This is the javascript/jquery:这是 javascript/jquery:
let timeArray = ["9","10", "11", "12", "13", "14", "15", "16", "17"]
let currentTime = parseInt(moment().format("H"));
for (i=0; i< 9; i++) {
if (currentTime < parseInt(timeArray[i])) {
$('.TextBoxColors-9').css('background-color', 'gray')
$('.TextBoxColors-10').css('background-color', 'gray')
$('.TextBoxColors-11').css('background-color', 'gray')
$('.TextBoxColors-12').css('background-color', 'gray')
}
if (currentTime == timeArray[i]) {
$('.TextBoxColors-13').css('background-color', 'Tomato')
}
if (currentTime > timeArray.indexOf("currentTime",currentTime)) {
$('.TextBoxColors-14').css('background-color', 'green')
$('.TextBoxColors-15').css('background-color', 'green')
$('.TextBoxColors-16').css('background-color', 'green')
$('.TextBoxColors-17').css('background-color', 'green')
}
}
These are two of the divs where I want this to happen:这是我希望发生这种情况的两个 div:
<!-- 2:00PM-->
<div class="input-group input-group-lg field-size Timer" >
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroup-sizing-lg">2 PM</span>
</div>
<textarea type="text" class="TextBoxColors-14 form-control" aria-label="2:00 PM"
aria-label describedby="inputGroup-sizing-sm"></textarea>
<button class="btn btn-primary" type="button" id="saveToDo-5"><i class="fa fa-floppy-o" style="font-size:18px;"></i>
</button>
</div>
<!-- 3:00PM-->
<div class="input-group input-group-lg field-size" >
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroup-sizing-lg">3 PM</span>
</div>
<textarea type="text" class="TextBoxColors-15 form-control" aria-label="3:00 AM"
aria-describedby="inputGroup-sizing-sm"></textarea>
<button class="btn btn-primary" type="button" id="saveToDo-0">
<i class="fa fa-floppy-o" style="font-size:18px;"></i>
</button>
</div>
This is close:这很接近:
$('.TextBoxColors-${i}')
But for template string literals you need to use back-ticks, not single-quotes:但是对于模板字符串文字,您需要使用反引号,而不是单引号:
$(`.TextBoxColors-${i}`)
Alternatively you can just concatenate the value to the string:或者,您可以将值连接到字符串:
$('.TextBoxColors-' + i)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.