[英]How to make div in loop clickable
我在 .JS 文件上有以下函數(我后來調用了一個 HTML 文件):
function writeDiv(){
x = 1
myArray.forEach(item => {
htmlText += '<div class="divsArray">';
htmlText += '<h5> Value of X: </h5>' + x;
htmlText += '</div>';
x++;
});
$('body').append(htmlText);
}
這會為我的數組中的每個條目(在本例中為 14)寫入一個 div,其中包含 X 的所述值。 我想要做的是,每次單擊 div 時,它都會通過窗口警報向我顯示已分配給它的 X 值。 我嘗試了一些東西,但我無法讓它工作,提前感謝您的幫助!
由於您似乎在使用 jQuery ( $
),我建議您注冊一個實時事件處理程序。
$(document)
.on('click', '.divsArray', (event)=>{
console.log(event);
console.log(event.currentTarget.getAttribute('id'));
// do further stuff here
});
我不知道你是什么,但就是這樣。 如果您使用某個變量而不是索引,它將不起作用,因為當 setTimeout 函數起作用時,每次迭代 x 的值都將相同。 如果您有其他問題,請鍵入。
function writeDiv() {
const myArray = [15,5,5];
let htmlText = "";
myArray.forEach((item, index)=> {
htmlText += `<div id="${index}" class="divsArray">`;
htmlText += '<h5> Value of X: </h5>' + x;
htmlText += '</div>';
setTimeout(()=>{
document
.getElementById(index)
.addEventListener("click",()=>{
alert(index + 1);
})},0)
});
document.getElementsByTagName('body')[0].innerHTML = htmlText;
}
writeDiv();
function writeDiv() { var temp = [100,150,200,300,400,500]; var innerHtml = ""; temp.forEach((item, index)=> { innerHtml += `<div class="divsArray">`; innerHtml += '<h5> Value of X: </h5><span>' + item +'</span>'; innerHtml += '</div>'; }); document.getElementsByTagName('body')[0].innerHTML = innerHtml; } writeDiv(); $(function() { $('.divsArray').click(function() { let addMoreRoomClone = $(this).find('span').html(); alert(addMoreRoomClone); }); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.