猿问

迭代数组并使用元素作为数据属性

如何循环遍历数组并将数组的元素添加到 div 内的 span 的 data 属性中?


html


<div id="wordBank">

    <span>Play</span>

    <span>Game</span>

</div>

jQuery


var 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>


蓝山帝景
浏览 94回答 1
1回答

叮当猫咪

您只需要循环单个数组并访问相应索引上的值。这里不需要嵌套循环。var words = ["play", "game"];$("#wordBank span").each(function(index){&nbsp; &nbsp; $(this).attr('data-word', words[index]);});&nbsp;&nbsp;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">&nbsp; &nbsp; <span>Play</span>&nbsp; &nbsp; <span>Game</span></div>
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答