簡體   English   中英

JS將eventListener添加到window創建的變量

[英]JS adding eventListener to window created variable

我有一些隨文檔一起加載的代碼; 為特定元素添加事件偵聽器。 我在一系列頁面上使用相同的偵聽器和相關功能。 在每個頁面上,特定元素是每個需要它的頁面的硬代碼,然后將元素饋送到偵聽器/函數。

但是我需要相同的偵聽器/函數來應用於其中一些頁面上的多個元素。 所以我試圖調整代碼以動態創建頁面變量並將每個元素分配給它自己的變量,然后將事件偵聽器添加到每個新創建的變量。 但它在我的代碼的addEventListener部分出錯。

//at the top of my document:
<script>
var fileInputIDs = [
     ['ceIcon','ceIconPreview'],
     ['cerImage','cerImagePreview']
] ;
</script>
...
// Page loads, including all the elements with the IDs defined in each fileInputIDs set.
// <input type="file" id="ceIcon">
// <div id="ceIconPreview" width="1200" height="300" style="width:25vw;margin-top:20px;"></div>
...

<script>
// after the document loads, this is at the end:
// create event listeners for each element defined in the array
for (var xx=0;xx<fileInputIDs.length;xx++) {
   window["fileInput_"+xx] = document.getElementById(fileInputIDs[xx][0]) ;
   window["fileInputPreview_"+xx] = document.getElementById(fileInputIDs[xx][1]) ;
 
   window["fileInput_"+xx].addEventListener('change',ev => {  ERROR <= "cannot read properties of undefined (reading 'addEventListener')"
      window['fileInputPreview_'+xx].innerHTML = '' ;
      this file = ev.target.files ;
      validateImage(files[0]) ;
   }) ;
}
</script>

只是委托

還有this file = ev.target.files; 無效 JavaScript

 const fileInputs = { 'ceIcon': 'ceIconPreview', 'cerImage': 'cerImagePreview' } document.addEventListener("change", e => { const tgt = e.target; if (tgt.matches("[type=file]")) { const previewId = fileInputs[tgt.id]; console.log(previewId) // do whatever you need to do with file and preview } })
 <input type="file" id="ceIcon"> <div id="ceIconPreview" width="1200" height="300" style="width:25vw;margin-top:20px;"></div>

如果 ID 遵循某種模式,您甚至不需要數組

 document.addEventListener("change", e => { const tgt = e.target; if (tgt.matches("[type=file]")) { const previewId = `${tgt.id}Preview`; console.log(previewId) // do whatever you need to do with file and preview } })
 <input type="file" id="ceIcon"> <div id="ceIconPreview" width="1200" height="300" style="width:25vw;margin-top:20px;"></div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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