gpt4 book ai didi

javascript - 将数组值附加到不同的容器

转载 作者:行者123 更新时间:2023-11-28 00:25:36 25 4
gpt4 key购买 nike

我想在各自的 div 中附加数组值,我有以下值数组,其“THINGS”指向名为 THING1THING2等等

["THING1", "ABC", "123", "THING2", "DEF", "456", "GHI", "789", "JKL", "123", "THING3", "MNO", "123", "PQR", "546"]

我正在检查 ID,如下

if(this.getAttribute('id')=="ITEM"+i)
{
//exits
}

我需要的只是将值附加到各自 div (ITEM) 中的指示器 (THING) 后面。

我的尝试:JS:

for (var i = 0; i <= myThings.length; i++) {
var item;
if (myThings[i] != null)
item = "ITEM1";
else if (myThings[i][i] != null)
item = "ITEM2";
else if (myThings[i][i] != null)
item= "ITEM3";
else if (myThings[i][i] != null)
item = "ITEM4";

if (myThings[i] == item)
{
var e = myThings[i];
$('#'+j).after(e);
}
};

HTML:

<div id="ITEM1"></div>
<div id="ITEM2"></div>
<div id="ITEM3"></div>
<div id="ITEM4"></div>

最佳答案

您不需要使用 after() 或测试它是否存在,如果找不到它,jQuery 将不会追加。

这是我的方法:

var myThings = ["THING1", "ABC", "123", "THING2", "DEF", "456", "GHI", "789", "JKL", "123", "THING3", "MNO", "123", "PQR", "546"];
var divs = "ITEM",
indicator = "THING",
t = 0;
j = 0;
$.each(myThings, function(i,v){
if (v.indexOf(indicator) !== -1) {
t = v.replace(indicator, "");
j = 1;
} else {
$('#'+divs+t).append($('<span />').attr('id', indicator + t + "_" + j).text(v));
j++;
}
});
span {
margin-right:15px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="ITEM1"></div>
<div id="ITEM2"></div>
<div id="ITEM3"></div>

关于javascript - 将数组值附加到不同的容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29528167/

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