Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
357 views
in Technique[技术] by (71.8m points)

JQuery - Set array element as attribute value for every <li>

I have an array arrayDescr and I need to use forEach to add to every <li> an attribute data-value. The value of data-value should be an arrayDescr element. For example I have three <li>'s and I have two arrayDescr elements. Two of three <li>'s should have attribute data-value arrayDescr[0], [1] and etc.

This code works but I need it to work in forEach:

$("#name1").attr("data-value", arrayDescr[0])

#name should be function(){return 'name' (i+1)}. In forEach this code returns undefined:

arrayDescr.forEach(function(item, index){
$("li").attr("data-value", item[index])}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here's a Vanilla Solution

var elem = document.querySelectorAll('li');

for (let i = 0; i < elem.length; i++) {
elem[i].setAttribute("data-value", "set value here, or determine how to make it dynamic"+i);
}

I haven't tested it on my end, but confident this should do what you want without JQuery and it be acceptable across many browsers (including mobile).

for (let i = 0; i < elem.length; i++) {
elem[i].setAttribute("data-value", (YourDescArray[i] !== undefined)?YourDescArray[i]:"problem");
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...