我正试图将带有一个函数的ID传递给另一个函数。控制台然后通知我有一个TypeError: document.getElementById(...) is null
。javascript文件被附加在末尾,我还尝试将代码添加到一个自执行函数中,但这并没有解决问题。
基本上,我想将addEventListener
添加到子类别div(按钮(,它们应该将其值传递给另一个函数。
错误指向此行let mainCategory = document.getElementById(recived_value).parentNode.firstChild(this.id);
,因此recived_value
为null。
欢迎任何帮助。非常感谢。
HTML:
<div class="wrapper">
<div class="main-category" id="box">
Boxes
</div>
<div class="sub-category" id="b_small">
Small Boxes
</div>
<div class="sub-category" id="b_medium">
Medium Boxes
</div>
<div class="sub-category" id="b_large">
Large Boxes
</div>
</div>
JS:
var subCategoryClass = document.querySelectorAll(".sub-category");
var subCategoryArray = Array.from(subCategoryClass);
for ( let i = 0; i < subCategoryArray.length; i++ ){
subCategoryArray[i].addEventListener("click", PassValue(this.id));
}
function PassValue(recived_value){
let subCategory = recived_value;
let mainCategory = document.getElementById(recived_value).parentNode.firstChild(this.id);
TwoArgFunc(mainCategory, subCategory);
}
有几个问题。我在下面的//评论中描述了它们。
编辑:根据你的评论,我改为普通函数定义。
var subCategoryClass = document.querySelectorAll(".sub-category");
var subCategoryArray = Array.from(subCategoryClass);
for ( let i = 0; i < subCategoryArray.length; i++ ){
subCategoryArray[i].addEventListener("click", function(ev) { PassValue(ev.target.id)} ); // need a function here, not just a statement
}
function PassValue(recived_value){
console.log(recived_value);
let subCategory = recived_value;
let mainCategory = document.getElementById(recived_value).parentNode.firstElementChild.id; // use firstElementChild because firstChild is a newline text node
console.log(mainCategory);
// TwoArgFunc(mainCategory, subCategory);
}
<div class="wrapper">
<div class="main-category" id="box">
Boxes
</div>
<div class="sub-category" id="b_small">
Small Boxes
</div>
<div class="sub-category" id="b_medium">
Medium Boxes
</div>
<div class="sub-category" id="b_large">
Large Boxes
</div>
</div>
以上PassValue
函数放入:
var that = this;
然后在PassValue
函数中传递that.id
:
... .firstChild(that.id);