我有这样简单的html结构:
<ul>
<li key="0">Text1</li>
<li key="1">Text2</li>
<li key="2">Text3</li>
</ul>
所以每个li
都有key属性,它是array(of objects)元素的索引。我想用密钥删除li
。所以我使用splice:
let keyBook = getAttribute("key");
...
books.splice(keyBook, 1);
此后li
元素的关键属性不实际。所以我的问题是:如何在拼接后从数组索引更新我的密钥?
答案 0 :(得分:1)
构建一个知道如何渲染自己的组件......
class Keys {
constructor(data, container) {
this._data = [].concat(data)
this.container = container;
this.render();
}
remove(key) {
this._data = this._data.filter(k => k !== key);
return this.render();
}
add(key) {
this._data = this._data.concat(key).sort();
return this.render();
}
render() {
this
.container
.innerHTML = this
._data
.reduce((res, text, index) => (
res.concat(`<li key="${index}">Text ${text}</li>`)
), '')
;
return this;
}
}
var cntr = document.getElementById('ListContainer');
var data = [1, 2, 3, 4, 5, 6];
var keys = new Keys(data, cntr);
window.setTimeout(() => keys.remove(3), 2000);
window.setTimeout(() => keys.add(67), 3500);
&#13;
<ul id="ListContainer"></ul>
&#13;