[英]How to add parameters in a function on a AddEventListener
我正在嘗試創建一個包含一些圖層的Web制圖應用程序,其想法是我有一些復選框,當我單擊它們時,該圖層被添加或刪除(我已經做過了),但是其中包含很多圖層,當然很多代碼,我意識到使用函數可以完成工作,但是經過數小時的工作后,它仍然無法正常工作,我准備放棄:
function turnon(idlayer, layer) {
var local = document.getElementById(layer);//verify whick checkbox is the one for the layer
if (local.checked == true) {
map.addOverlay(layer);//an OpenLayers method to add the layer to the map
} else {
map.removeOverlay(layer);
}
}
var wmsSector=document.getElementById('sector')//This is the checkbox
wmsSector.addEventListener("click", turnon);
我不知道如何在addEventListener
處理程序上添加參數的事情我已經嘗試過:
wmsSector.addEventListener("click",turnon('wmsSector',sector))
我感謝您能提供的任何幫助,因為目前該應用程序可以運行,但我認為它可以更優雅。
我將在附加偵聽器時更加通用,以便復選框提供要附加的疊加層的ID或名稱,例如
// For testing var map = { addOverlay: function(layer) { console.log(layer + ' added'); }, removeOverlay: function(layer) { console.log(layer + ' removed'); } }; // Toggle layer on or off function toggleLayer(evt) { this.checked? map.addOverlay(this.value) : map.removeOverlay(this.value); } // Add listener to each layer checkbox window.onload = function() { [].forEach.call(document.querySelectorAll('.layerToggle'), function(node) { node.addEventListener('click', toggleLayer, false); }); }
<label for="wmsSector"><input type="checkbox" id="wmsSector" value="wmsSector" class="layerToggle"> WMS Sector</label><br> <label for="vegetation"><input type="checkbox" id="vegetation" value="vegetation" class="layerToggle"> Vegetation</label><br> <label for="adminBoundaries"><input type="checkbox" id="adminBoundaries" value="adminBoundaries" class="layerToggle"> Admin Boundaries</label>
我使用過value屬性,但您也可以使用data- *屬性,例如data-mapLayer="wmsSector"
或類似屬性。
使用匿名功能,
wmsSector.addEventListener("click",function(){
turnon('wmsSector',sector);
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.