[英]pass arguments inside button onclick function inside bindPopUp in leaflet
我試圖在傳單的bindPop內部創建一個按鈕偵聽器功能。 但是it does not read parameter of onclick function
。 在下面的代碼中, alertConfirmed()function works fine
對我來說alertConfirmed()function works fine
, but
filterEventsBasedOnCluster(feature) does not read the parameter 'feature'
。 它說功能未定義 。 特征是一個對象 。
這是代碼:
layer.bindPopup('<div id="alert">Found...!<input type="button" value="Please confirm" onclick="alertConfirmed()"> <input type="button" id="create" value="see patients" onclick="filterEventsBasedOnCluster(feature)"><table id="table"></table></div>')
`
任何幫助深表感謝。
如果通過onclick
HTML屬性附加事件處理程序,則無法控制該處理程序接收的參數。 讓我引用這些文檔:
傳遞給指定事件處理程序函數的單個參數是
MouseEvent
對象。 在處理程序中,this
將是觸發事件的元素。
傳遞自定義參數的方法是通過使函數返回僅接收事件引用的函數來定義閉包。
這與《 Leaflet.contextmenu回調 》和《 Leaflet標記事件在錯誤的時間觸發 》中所述的解決方案完全相同。
閱讀。 我是認真的。
所以最后它應該看起來像:
function getHandlerForFeature(feat) { // A function...
return function(ev) { // ...that returns a function...
console.log(feat); // ...that has a closure over the value.
}
}
layer.bindPopup("<button id='mybutton'>Foo!</button>")
// The button doesn't exist in the DOM until the popup has been opened, so
layer.on('popupopen', function(){
L.DomEvent.on(
document.getElementById('mybutton'),
'click',
getHandlerForFeature(layer) // The result of this call is the event handler func.
);
});
請注意,您不能使用onclick="code"
語法,因為您需要創建一串可運行的代碼,並且該代碼將只能訪問全局范圍內的變量。 當然,您可以JSON.stringify()
您的數據,但您將無法在外部引用變量。
嘗試這個:
我只是在糾正錯誤的部分:
onclick="filterEventsBasedOnCluster('+feature+')"
您沒有正確傳遞變量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.