简体   繁体   English

如何使循环中的 div 可点击

[英]How to make div in loop clickable

I have the following function on a .JS file (that I later call on an HTML file):我在 .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); 
   }

This writes me one div, with the said value of X, per entry on my array (in this case 14).这会为我的数组中的每个条目(在本例中为 14)写入一个 div,其中包含 X 的所述值。 What I want to do is, everytime I click on a div it shows me, through a window alert, the value of X that has been assigned to it.我想要做的是,每次单击 div 时,它都会通过窗口警报向我显示已分配给它的 X 值。 I tried some things but I couldn't get it to work, thanks for the help in advance!我尝试了一些东西,但我无法让它工作,提前感谢您的帮助!

As you're seem to use jQuery ( $ ), I would recommend to register a live event handler.由于您似乎在使用 jQuery ( $ ),我建议您注册一个实时事件处理程序。

$(document)
  .on('click', '.divsArray', (event)=>{
    console.log(event);
    console.log(event.currentTarget.getAttribute('id'));
     
    // do further stuff here
  });

I don't know is it what you what, but here is it.我不知道你是什么,但就是这样。 If you use some variable instead of index, it won't work, cuz when function of setTimeout works, the value of x will be same for every iteration.如果您使用某个变量而不是索引,它将不起作用,因为当 setTimeout 函数起作用时,每次迭代 x 的值都将相同。 If you have some other questions type.如果您有其他问题,请键入。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM