[英]javascript/HTML: Bind event handler function with object as argument in HTML string literal
使用我正在開發的電子應用程序,我未能將對象傳遞到圖像的onclick
事件處理程序中。 事件處理程序在 HTML 中指定,但 HTML 是 JS 中的字符串文字。
這個想法是將類My
的對象傳遞到對象代碼嘗試生成的圖像控件的事件處理程序中,請參閱下面的代碼
class My {
constructor() {
this.id = '123';
}
GenerateCtrl() {
let html = `
<div class="myclass" id="my-${this.id}">
<img class="img-btn" id="do-${this.id}" src="images/btn-img.png" role="button" onclick="Do(this, '${this}')">
</div>
`;
return html;
}
}
上面的 HTML 將是我頁面的一部分。
這是事件處理程序
function Do(img, myobj) {
alert(JSON.stringify(myobj));
}
構建頁面時的調用方代碼:
const sect = document.querySelector(.myclass);
var myObj = new My();
sect.innerHTML = myObj.GenerateCtrl();
我可以毫無問題地看到頁面上的圖像控件。
單擊圖像時,我希望看到顯示對象內容的警報。
但我在警報中只能看到"[object Object]"
。
這告訴我該對象不是作為參數通過該處理程序函數,而是作為轉換后的字符串。
正確的方法是將 HTML 作為元素插入,而不是 HTML 字符串,以便可以預先將偵聽器附加到內部<img>
。 將事件偵聽器附加到您已經引用其父元素的元素非常便宜,基本上沒有性能損失。 這是代碼的外觀,使用createElement
創建外部元素,然后使用appendChild
插入它:
function Do(my) { console.log(my); } class My { constructor() { this.id = '123'; } GenerateCtrl() { const div = document.createElement('div'); Object.assign(div, { id: `my-${this.id}`, className: 'img-btn' }); div.innerHTML = `<img class="img-btn" id="do-${this.id}" src="images/btn-img.png" role="button">`; div.children[0].addEventListener('click', () => Do(this)); return div; } } var myObj = new My(); document.querySelector('.myclass').appendChild(myObj.GenerateCtrl());
<div class="myclass"></div>
內聯處理程序有太多問題:
window.Do
函數)with
語句中運行 - 一個用於document
,一個用於當前元素最好避開它們。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.