簡體   English   中英

將 this.id 傳遞給另一個 function 返回 null 錯誤

[英]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_valuenull

歡迎任何幫助。 謝謝你。

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM