簡體   English   中英

如何將 data- 屬性動態添加到 html 元素數組

[英]How can i dynamically add data- attribute to an array of html elements

我有一個 html 圖像元素的節點列表,我使用擴展運算符將其轉換為數組,所以現在我有一個像這樣的圖像元素數組[img.item, img.item, img.item, img.item, img.item, img.item] 這就是我想要做的,我想根據數組中的 position 為數組中的每個元素動態添加一個數據屬性(data-id); 這樣第一個元素的 data-id 為 0,第二個元素的 data-id 為 1,第三個元素的 data-id 為 2,最后一個元素的 data-id 為 5。這是代碼

<div class="container">
    <img src="https://image.shutterstock.com/image-photo/surreal-concept-roll-world-dice-260nw-1356798002.jpg" alt="" class="item" >

    <img src="https://images.unsplash.com/photo-1494253109108-2e30c049369b?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8Mnx8cmFuZG9tJTIwZm9vZCUyMHN0b3JlfGVufDB8fDB8fA%3D%3D&w=1000&q=80" alt="" class="item" >

    <img src="https://www.thedesignwork.com/wp-content/uploads/2011/10/Random-Pictures-of-Conceptual-and-Creative-Ideas-02.jpg" alt="" class="item" >

    <img src="http://images2.fanpop.com/images/photos/5900000/Randomness-random-5997130-1280-800.jpg" alt="" class="item" >

    <img src="https://images.unsplash.com/photo-1508138221679-760a23a2285b?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8NXx8cmFuZG9tfGVufDB8fDB8fA%3D%3D&w=1000&q=80" alt="" class="item" >

    <img src="https://www.computerhope.com/jargon/r/random-dice.jpg" alt="" class="item" >

</div>

<script> const images = document.querySelectorAll(".item")
    const imageArray = [...images] </script>

請問我該怎么做 go?

用這個:

imageArray.forEach(function(val, index){
    val.setAttribute('data-id', index);
});

迭代您的圖像數組,然后您可以使用setAttribute function 設置數據屬性。 像那樣:

 const images = document.querySelectorAll(".item") images.forEach((i, index) => { i.setAttribute('data-position', (index + 1)); }) console.log(images[1])
 img { width:200px; }
 <div class="container"> <img src="https://image.shutterstock.com/image-photo/surreal-concept-roll-world-dice-260nw-1356798002.jpg" alt="" class="item" > <img src="https://images.unsplash.com/photo-1494253109108-2e30c049369b?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8Mnx8cmFuZG9tJTIwZm9vZCUyMHN0b3JlfGVufDB8fDB8fA%3D%3D&w=1000&q=80" alt="" class="item" > <img src="https://www.thedesignwork.com/wp-content/uploads/2011/10/Random-Pictures-of-Conceptual-and-Creative-Ideas-02.jpg" alt="" class="item" > <img src="http://images2.fanpop.com/images/photos/5900000/Randomness-random-5997130-1280-800.jpg" alt="" class="item" > <img src="https://images.unsplash.com/photo-1508138221679-760a23a2285b?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8NXx8cmFuZG9tfGVufDB8fDB8fA%3D%3D&w=1000&q=80" alt="" class="item" > <img src="https://www.computerhope.com/jargon/r/random-dice.jpg" alt="" class="item" > </div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM