在下面的代碼中,我希望每個按鈕都提醒自己的 id。問題是在所有其他按鈕中只有第一個按鈕的 id 會收到警報。document.getElementById('button').addEventListener('click', function() { addElement();}, false);function addElement() { di3 = rngc(10, 100001); document.getElementById('demo').insertAdjacentHTML('afterbegin', '<button id="' + di3 + '" type="button" >newb</button>'); document.getElementById(di3).addEventListener('click', function() { al(di3); }, false);}function al(x) { console.log(x);}function rngc(A, B) { var d = new Date(), n = d.getMilliseconds(); return 'ig' + Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, A) + Math.floor(Math.random() * (B)) + n;}<button id="button" type="button">add</button><div id="demo"></div>注 1:我的實際代碼將許多 html 元素作為一個字符串加載。更新:我不想使用 onclick 屬性;addEventListener 是我的目標。
使用 addEventListener 加載 HTML 內容的問題
繁星coding
2021-09-30 17:57:34