gpt4 book ai didi

javascript - 为什么在 removeItem 中不需要括号?为什么 li.onclick = removeItem 必须在 newItem() 函数内?

转载 作者:行者123 更新时间:2023-11-30 11:04:15 24 4
gpt4 key购买 nike

  1. 为什么 removeItem 不需要括号?
  2. 为什么 li.onclick = removeItem 必须在 newItem() 函数内?
  3. li.onclick 事件发生时的逻辑顺序是什么? newItem() 是否被执行?如果是这样,它是如何触发的?

我以为只有回车键会触发newItem(),既然li.onclick = removeItem在newItem()里面,为什么点击会触发呢?

免责声明:我在网上找到了这段代码,但我不明白这些细节,希望大家帮忙。谢谢!

html

<input id="input" placeholder="What needs to be done?">

<ul id="list"></ul>

JavaScript

        function newItem() {
var item = document.getElementById("input").value;
var ul = document.getElementById("list");
var li = document.createElement("li");
if (document.getElementById("input").value != ""){
li.appendChild(document.createTextNode(item));
ul.appendChild(li);
document.getElementById("input").value = "";
}
li.onclick = removeItem;
}


document.body.onkeyup = function(e) {
if (e.keyCode == 13) {
newItem();
}
}

function removeItem(e) {
e.target.parentElement.removeChild(e.target);
}

最佳答案

您不需要括号,因为您正在存储对函数的引用。稍后将调用该函数。请参阅以下示例:

function f1() {
console.log("f1 called");
}

var function_storage = f1;

function_storage();

li 声明为 newItem 的局部变量,因此它只能在函数内部使用。

onclick 事件发生时,removeItem 函数的调用方式与上述示例中的 f1 相同。

关于javascript - 为什么在 removeItem 中不需要括号?为什么 li.onclick = removeItem 必须在 newItem() 函数内?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56317386/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com