使用for循环删除按钮



大家晚上好。我正在学习javascript。在学习了一些基础知识后,我决定制作待办事项列表,并从互联网上获得了待办事项列表代码。但我有一个问题。我的代码:

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
</head>
<body>
<div>
<h2>ToDo</h2>
<input type="text" id="inputum" />
<button onclick="fonksiyonum()">Ekle</button>
</div>
<ul id="yeniUl"></ul>
<script>
function fonksiyonum() {
var liEkle = document.createElement('li');
var inputtaYazanlar = document.getElementById('inputum').value;
var textim = document.createTextNode(inputtaYazanlar);
liEkle.appendChild(textim);
document.getElementById('yeniUl').appendChild(liEkle);
document.getElementById('inputum').value = '';
var button = document.createElement('BUTTON');
var hiks = document.createTextNode('u00D7');
button.appendChild(hiks);
liEkle.appendChild(button);
button.className = 'close';
var close = document.getElementsByClassName('close');
for (i = 0; i < close.length; i++) {
close[i].onclick = function () {
var div = this.parentElement;
div.style.display = 'none';
};
}
}
</script>
</body>
</html>

据我所知,for (i = 0; i < close.length; i++)用于获取button.close[i].onclick = function ()显示按下按钮时将运行的功能。但是为什么close[i]字母"i"在这里是什么意思呢?之后是CCD_ 4。我不懂this.parentElement。如果有人能向我解释母元素的概念,我会很高兴。

close.length实际上是所有按钮的列表/数组。您可以通过getElementsByClassName中的元素来判断
因此,您正在循环使用所有关闭按钮,并为每个按钮添加一个onclick()方法。

list = [btn0, btn1]
list.length // length = 2
// for i=0; i<list.length; i++
// 1st pass, i == 0:
list[0] // btn0
// 2st pass, i == 1:
list[1] // btn1
// 3rd pass, i == 2
// i is not less than length, 2, end.

对于parentElement,我总是看标签,只需向左上翻1个标签;那是家长这就是为什么格式化很重要,让它变得容易

<div>                                               <!-- <- Parent -->
<h2>ToDo</h2>
<input type="text" id="inputum" />
<button onclick="fonksiyonum()">Ekle</button>     <!-- <- Button --->
</div>

最新更新