将项目从数组中渲染到DOM中,并为每次单击更改值

时间:2019-02-08 18:52:47

标签: javascript dom

所以我得到了这段代码,用于从DOM内部的数组中推送所有项目。

如何使点击事件适用于每个项目?

编辑:

let items = {
  item1: {
    cost: 2200,
    owned: 0,
    type: "item type",
    name: "item1",
    desc: "item1 desc.",
    img: "img/item1.gif"
  },
  item2: {
    cost: 4400,
    owned: 0,
    type: "item type",
    name: "item2",
    desc: "item2 desc.",
    img: "img/item2.gif"
  },
};

for (let key of Object.keys(items)) {
  if (items[key].owned==0) {
    var el = document.createElement('div');
    var domString = '<div class="item"><div class="w3 h3 bg-center contain" style="background-image:url(' + items[key].img + ')"></div><span>'+ items[key].name +'</span><span>Price: '+ items[key].cost +'</span><span>'+ items[key].desc +'</span></div>';
    el.innerHTML =  domString;
    el.addEventListener('click', function() {
      items[key].owned = 1;
      console.log(items[key].name + ' ' + items[key].owned);
    });
    document.getElementById('shop').appendChild(el.firstChild);
  }
}

我想在点击时更改一个项目变量。 事件侦听器在此代码中不起作用。

1 个答案:

答案 0 :(得分:1)

利用对象键分配ID,然后添加事件监听器

shortest_repeating_sequence([4, 2, 7, 4, 6])  # no pattern
[4, 2, 7, 4, 6]
shortest_repeating_sequence([2, 3, 1, 2, 3])  # pattern doesn't repeat fully
[2, 3, 1]
shortest_repeating_sequence([2, 3, 1, 2])     # pattern doesn't repeat fully
[2, 3, 1]
shortest_repeating_sequence([8, 9, 8, 9, 8, 9, 8])
[8, 9]
shortest_repeating_sequence([1, 1, 1, 1, 1])
[1]
shortest_repeating_sequence([])
[]

或者您可以简单地在使用for (let key of Object.keys(items)) { if (items[key].owned==0) { var el = document.createElement('div'); var domString = '<div id="' + items[key] + '"><div class="w3 h3 bg-center contain" style="background-image:url(' + items[key].img + ')"></div><span>'+ items[key].name +'</span><span>Price: '+ items[key].cost +'</span><span>'+ items[key].desc +'</span></div>'; el.innerHTML = domString; document.getElementById('shop').appendChild(el.firstChild); } } for (let key of Object.keys(items)) { document.getElementById(items[key]).addEventListener('click', function() { items[key].owned = 1 }); }

创建的div元素上分配侦听器
document.createElement