如何使循环中的div可单击

1l5u6lss  于 2021-09-13  发布在  Java
关注(0)|答案(3)|浏览(353)

我在.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值。我尝试了一些东西,但我无法让它发挥作用,提前谢谢你的帮助!

dldeef67

dldeef671#

正如您似乎在使用jquery一样( $ ),我建议注册一个实时事件处理程序。

$(document)
  .on('click', '.divsArray', (event)=>{
    console.log(event);
    console.log(event.currentTarget.getAttribute('id'));

    // do further stuff here
  });
jtoj6r0c

jtoj6r0c2#

我不知道这是什么,但这是它。如果使用某个变量而不是索引,它将不起作用,因为当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();
uqxowvwt

uqxowvwt3#

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>

相关问题