我想在各自的div中附加数组值,我将使用" THINGS" taht指向名为THING1
,THING2
的相应div,等等
["THING1", "ABC", "123", "THING2", "DEF", "456", "GHI", "789", "JKL", "123", "THING3", "MNO", "123", "PQR", "546"]
我正在检查ID,如下所示
if(this.getAttribute('id')=="ITEM"+i)
{
//exits
}
我需要的是将指标(THING)之后的值附加到它们各自的div(ITEM)中。
我的尝试: 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>
答案 0 :(得分:1)
你不需要使用after()
或测试jQuery如果找不到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++;
}
});
&#13;
span {
margin-right:15px;
}
&#13;
<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>
&#13;
答案 1 :(得分:0)
基本上,你可以使用i变量遍历项目并在div之后添加它们:
var myThings = ["THING1", "ABC", "123", "THING2", "DEF", "456", "GHI", "789", "JKL", "123", "THING3", "MNO", "123", "PQR", "546"];
var divs = $("div[id^='ITEM']"); //this selects all divs that have an id starting with "ITEM"
for (var i = 0; i <= myThings.length; i++) {
var item = $(divs[i]); //this selects the current item
item.after("<p>" + myThings[i] + "</p>"); //this adds a paragraph after the item
}
这将在第一个div结束后添加第一个项目,在第二个div结束后添加第二个项目等。
此外,您需要一个html元素发送到after()函数,而不仅仅是文本字符串。在示例中,我将其包装在段落标记中以执行此操作。
此外,我不确定您是否要使用after()(在div结尾后添加项目)或append()(在div中添加项目)。你可以改变.after(to .append(如果你想追加。