【问题标题】:Setting data-attributes with loop? (more below)用循环设置数据属性? (更多下文)
【发布时间】:2021-06-30 04:44:47
【问题描述】:

我想为通过数组循环创建的 div 设置数据属性。

let myLibrary = [ ] //the array

for (const book of myLibrary){
    let cover = document.createElement('div')
    cover.textContent =`title: ${book.title}`
        cover.classList.add('bookStyle')     //adding class for css
        books.appendChild(cover)             //appending to class='books'
    }

为书籍添加删除按钮:

const addedBooks = document.querySelectorAll('.bookStyle')
    addedBooks.forEach(book => {
        book.addEventListener('click', removeBook)

    let del = document.createElement('BUTTON');
    del.classList.add('delBtn')
    del.textContent = 'x'
    book.appendChild(del)
}) 

我想做这样的事情: (循环遍历子元素,添加数据属性)

for (let i = 0; i < myLibrary.length; i++){
        book.setAttribute('data-index', i)
    }

最后,“书籍”列表看起来像这样:

<div class = 'bookStlye' data-index: 0> Title of book</div>
<div class = 'bookStlye' data-index: 1> Title of book</div>
<div class = 'bookStlye' data-index: 2> Title of book</div>
<div class = 'bookStlye' data-index: 3> Title of book</div>

任何帮助表示赞赏!

【问题讨论】:

  • 您目前得到的结果是什么?因为查看问题中的细节,似乎一切都应该正常工作。
  • book 在设置属性的 for 循环中未定义。您在开发工具控制台中看到了哪些错误?
  • 根据您的代码,由于books存储在myLibrary中,您应该在循环中将book替换为myLibrary[i]。或者像使用 addedBooks 一样使用 forEach 循环
  • 或者像以前一样使用for of
  • 使用book.dataset.index = i

标签: javascript html css loops dom


【解决方案1】:

const books = document.querySelectorAll('.bookStyle')
books.forEach((book, i) => book.setAttribute('data-index', i))
<div class='bookStyle'> Title of book</div>
<div class='bookStyle'> Title of book</div>
<div class='bookStyle'> Title of book</div>
<div class='bookStyle'> Title of book</div>

【讨论】:

    【解决方案2】:

    感谢所有回复,这对我有用:

    const books = document.querySelectorAll('.bookStyle') book.forEach((book, i) => book.setAttribute('data-index', i))

    【讨论】:

      猜你喜欢
      • 2018-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多