gpt4 book ai didi

JavaScript 循环逻辑

转载 作者:行者123 更新时间:2023-12-02 18:25:00 25 4
gpt4 key购买 nike

我会用文字+截图的方式来解释

我有三个容器,其中包含以下内容。

enter image description here

它们每个都有不同的 id 和相同的类。

<div id="container" class='list-cont'>
<h2> One Two Three Four</h2>
</div>

<div id="container-1" class='list-cont'>
<h2> Four Five Six </h2>
</div>

<div id="container-2" class='list-cont'>
<h2> Seven Eight Nine Ten Eleven</h2>
</div>

我这样做的目的是,让每个容器的前半部分单词变成不同的颜色,剩下的也变成不同的颜色,就像这个。但主要问题是,代码不断循环,我不知道为什么会发生这种情况,页面不停地重新加载。

enter image description here

代码:

//Count total number of div's which has a class of list-cont
var div_items = $(".list-cont").length;

for (var q = 1; q <= div_items; q++) {
//If 1 the container who doesn't have "-" will get an update
if (q = 1) {

//Get value of h2 of the container who doesn't have "-"
var s = $('div#container h2').html();

s = s.replace(/(^\s*)|(\s*$)/gi,"");
s = s.replace(/[ ]{2,}/gi," ");
s = s.replace(/\n /,"\n");

//Number of words
var str_length = s.split(' ').length;

//Words in an array
var str_array = s.split(' ');

//Get total of first half of words
var len_first = Math.round(str_length / 2);

//Delete Value of h2
$("div#container h2").html('');

for (var ctr = 0; ctr < str_length; ctr++) {
if (ctr >= len_first) {
$("div#container h2").append(" <font color='#fdbd16'>"+ str_array[ctr] +"</font> ");
} else {
$("div#container h2").append(" " + str_array[ctr] + " ");
}
}
} else {
//Container has "-" like container-1 or container-2

//Get value of h2 of the container who doesn't have "-"
var s = $('div#container-'+ q +' h2').html();

s = s.replace(/(^\s*)|(\s*$)/gi,"");
s = s.replace(/[ ]{2,}/gi," ");
s = s.replace(/\n /,"\n");

//Number of words
var str_length = s.split(' ').length;

//Words in an array
var str_array = s.split(' ');

//Get total of first half of words
var len_first = Math.round(str_length / 2);

//Delete Value of h2
$("div#container-"+ q +" h2").html('');

for (var ctr = 0; ctr < str_length; ctr++) {
if (ctr >= len_first) {
$("div#container-"+ q +" h2").append(" <font color='#fdbd16'>"+ str_array[ctr] +"</font> ");
} else {
$("div#container-"+ q +" h2").append(" " + str_array[ctr] + " ");
}
}
}
}

最佳答案

你的代码有很多问题,但让它无限循环的原因是这个

for (var q = 1; q <= div_items; q++) {
if (q = 1) {
// q is now 1
// so it stays lower than div_items (3) forever, the loop continues
}
}

您想要检查 q 的值,而不是设置它

if (q == 1) {    

关于JavaScript 循环逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18483291/

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