我正在构建待办事项列表:
我打算做的是每个任务,如果我点击它应该转换为黄色的刻度符号意味着完成。现在的问题是,对于第一个元素,它工作得很好,即它在白色和黄色之间切换(意味着任务已完成),但如果我添加了多个任务,那么它就不起作用(根本没有动作)。我不打算用数字添加动态id或类。我该如何解决它们。
现在我在javascript返回这个较低的部分,返回的html如下所示:
<div class="row datasection">
<div class="todo">
<div class="databox col s6 offset-s1 waves-effect">
<p class="checkglyph1 checkglyph2">Task no 1</p>
<a>
<i class="material-icons checkglyph checkglyph1 checkglyph2 glyphcolor">check</i>
</a>
</div>
</div>
</div>
JavaScript代码:
var calendardata = document.getElementById('date1');
var addbutton = document.querySelector('.addbutton');
var todo = document.querySelector('.todo');
addbutton.addEventListener('click', function() {
/* body to return the html */
if (data.value) {
var newdiv = document.createElement("div"); // Create a <button> element
newdiv.classList.add("databox", "col", "s6", "waves-effect");
//console.log(newdiv);
todo.appendChild(newdiv);
//console.log(newdiv.parentNode);
var newpar = document.createElement("p");
newpar.classList.add("checkglyph1", "checkglyph2");
var node = document.createTextNode(data.value + "." + " " + calendardata.value);
var newa = document.createElement("a");
newdiv.appendChild(newa)
var newglyph = document.createElement("i");
newglyph.classList.add("material-icons", "checkglyph", "checkglyph1", "checkglyph2", "glyphcolor");
var node1 = document.createTextNode("check");
newa.appendChild(newglyph);
newglyph.append(node1);
newpar.appendChild(node);
newdiv.appendChild(newpar);
data.value = "";
calendardata.value = "";
created = true;
console.log("before glyh created");
//code to perform action on the click of the tick symbol
var glyph = document.querySelector(".glyphcolor");
var par = document.getElementsByClassName('checkglyph2');
console.log(glyph);
console.log(par.length);
console.log(this);
glyph.addEventListener('click', function() {
console.log("This is :")
console.log(this);
glyph.classList.toggle("checkglyph1");
console.log(this)
})
}
})
答案 0 :(得分:1)
用项目换行切换按钮,将颜色更改为同一个父级。
单击按钮时,事件处理程序this
将指向该按钮。您可以查询它的父项,然后导航到项目并切换类使其变为黄色,或手动更改此元素的内联样式。
答案 1 :(得分:1)
首先,负责将任务标记为完成的代码应该在click事件之外(即addbutton
),同样你必须使用querySelectorAll获取所有.glyphcolor
元素,迭代并为每一个添加事件监听器:
var glyph= document.querySelectorAll(".glyphcolor");
for (var i = 0; i < glyph.length; i++) {
glyph[i].addEventListener('click', function(event) {
this.classList.toggle("checkglyph1");
});
}
请记住,querySelector始终会返回第一个匹配的元素,这就是为什么它仅适用于第一个任务
编辑:在创建任务期间创建字形侦听器:添加每个任务,将侦听器附加到i
元素:
...
var newglyph = document.createElement("i");
newglyph.classList.add("material-icons", "checkglyph", "checkglyph1", "checkglyph2", "glyphcolor");
newglyph.addEventListener('click', function(event) {
this.classList.toggle("checkglyph1");
});
var node1 = document.createTextNode("check");
...