如何循环遍历数组并将数组的元素添加到 div 内的 span 的 data 属性中?html<div id="wordBank"> <span>Play</span> <span>Game</span></div>jQueryvar words = ["play", "game"];$.each(words, function(index, value){ $("#wordBank span").each(function(){ $(this).attr('data-word', value); });});电流输出<div id="wordBank"> <span data-word="game">Play</span> <span data-word="game">Game</span></div>所需输出<div id="wordBank"> <span data-word="play">Play</span> <span data-word="game">Game</span></div>
1 回答
叮当猫咪
TA贡献1776条经验 获得超12个赞
您只需要循环单个数组并访问相应索引上的值。这里不需要嵌套循环。
var words = ["play", "game"];
$("#wordBank span").each(function(index){
$(this).attr('data-word', words[index]);
});
console.log(document.querySelector('#wordBank').outerHTML)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="wordBank">
<span>Play</span>
<span>Game</span>
</div>
添加回答
举报
0/150
提交
取消