[英]passing this.id to another function returns null error
我正在尝试将带有 function 的 ID 传递给另一个 function。 然后控制台通知我有一个TypeError: document.getElementById(...) is null
。 javascript 文件附加在末尾,我还尝试将代码添加到自执行 function 中,但这并没有解决问题。
基本上我想为子类别 div(按钮)添加一个事件监听器,它们应该将它们的值传递给另一个addEventListener
。
错误指向这一行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);
}
有几个问题。 我在下面的//评论中描述了它们。
编辑:根据您的评论,我更改为普通的 function 定义。
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
function 放:
var that = this;
然后在您的PassValue
function 中传递that.id
:
... .firstChild(that.id);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.