[英]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
.我有一个数组
arrayDescr
,我需要使用forEach
添加到每个<li>
属性data-value
。 The value of data-value
should be an arrayDescr
element. data-value
应该是一个arrayDescr
元素。 For example I have three <li>
's and I have two arrayDescr
elements.例如,我有三个
<li>
和两个arrayDescr
元素。 Two of three <li>
's should have attribute data-value
arrayDescr[0]
, [1] and etc.三个
<li>
中的两个应该具有属性data-value
arrayDescr[0]
、 [1] 等。
This code works but I need it to work in forEach:此代码有效,但我需要它在 forEach 中工作:
$("#name1").attr("data-value", arrayDescr[0])
#name should be function(){return 'name' (i+1)}. #name 应该是 function(){return 'name' (i+1)}。 In forEach this code returns
undefined
:在 forEach 中,此代码返回
undefined
:
arrayDescr.forEach(function(item, index){
$("li").attr("data-value", item[index])}
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).我还没有对它进行测试,但是相信这应该可以在没有 JQuery 的情况下满足您的要求,并且它在许多浏览器(包括移动设备)中都是可以接受的。
for (let i = 0; i < elem.length; i++) {
elem[i].setAttribute("data-value", (YourDescArray[i] !== undefined)?YourDescArray[i]:"problem");
}
I think you should be iterating over li
elements and set their attributes in the forEach
like我认为您应该迭代
li
元素并在forEach
中设置它们的属性,例如
$("li").each(function(i,item){
if(arrayDescr.length > i)
$(item).attr("data-value",arrayDescr[i]);
});
You can iterate li element and assign attr like below您可以迭代 li 元素并分配 attr 如下所示
$( "li" ).each(function( index ) {
if(index<arrayDescr.length){
$( this ).attr("data-value", arrayDescr[index]) ;
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.