Javascript 需要返回的appendToLi()函数?
快速提问。。。使用appendToLi时需要返回'element'变量的原因是什么?如果删除该行,代码将不会向列表中添加任何内容。这让我很困惑,因为appendToLi函数调用没有将元素返回到任何对象 例如,如果它看起来像这样,我会理解的Javascript 需要返回的appendToLi()函数?,javascript,Javascript,快速提问。。。使用appendToLi时需要返回'element'变量的原因是什么?如果删除该行,代码将不会向列表中添加任何内容。这让我很困惑,因为appendToLi函数调用没有将元素返回到任何对象 例如,如果它看起来像这样,我会理解的 let element = appendToLi(property, value, text); 但事实并非如此。我有 appendToLi(property, value, text); 这: 。。。如果appendToLi()未返回元素,则引发错误并
let element = appendToLi(property, value, text);
但事实并非如此。我有
appendToLi(property, value, text);
这:
。。。如果appendToLi()
未返回元素,则引发错误并中断脚本执行
上述代码行与此等效:
var element = appendToLi('label', 'textContent', 'Completed');
element.appendChild(createElement('input', 'type', 'checkbox'));
在这里,更容易看到
appendToLi()时发生的情况
不返回任何内容:元素
变为未定义
,然后您尝试在其上调用名为appendChild
的方法,该方法会引发错误,因为未定义
没有任何方法或属性。我知道提交表单时您正在创建元素。因为我不知道你为什么要做什么,所以我猜我能做什么。在下面的代码部分:
//Function declaration (Adds the created element to the list)
function appendToLi(elementName, property, value){
const element = createElement(elementName, property, value);
li.appendChild(element);
return element;
}
//Creates the list item
const li = document.createElement('li');
//Appends all children to the list item.
appendToLi('span', 'textContent', text);
在这里,您在声明函数后创建了liappendToLi函数,并在函数声明之前尝试声明。这可能会有帮助。这是因为没有返回任何内容。。。。功能永远不会结束?我是JS的新手,对我来说是如此赤裸裸;P@CollinDeSoto这是因为对
appendToLi()
返回的任何内容调用名为appendChild
的方法。如果appendToLi()
没有返回您试图调用的任何内容,则在undefined
上调用appendChild()
,这会引发错误,进而导致脚本在该点停止。请参阅我的最新答案。
var element = appendToLi('label', 'textContent', 'Completed');
element.appendChild(createElement('input', 'type', 'checkbox'));
//Function declaration (Adds the created element to the list)
function appendToLi(elementName, property, value){
const element = createElement(elementName, property, value);
li.appendChild(element);
return element;
}
//Creates the list item
const li = document.createElement('li');
//Appends all children to the list item.
appendToLi('span', 'textContent', text);