简体   繁体   English

向循环内动态生成的 DIV 添加点击事件,显示弹出 window 并在 Javascript 中为每个 DIV 提供不同的文本

[英]Add a click event to dynamically generated DIVs inside a loop that show a popup window with different text for each of them in Javascript

What I'm try to achieve is to dynamically create buttons through javascript/jquery and attach a "click" event on them, so that each button will show up a popup window with some text inside that is different for every iteration (the data is taken from an array).我试图实现的是通过 javascript/jquery 动态创建按钮并在它们上附加一个“点击”事件,这样每个按钮都会显示一个弹出窗口 window,其中的一些文本对于每次迭代都是不同的(数据是取自数组)。 However I'm struggling with passing the data inside the "click" function, because at the moment the scripts only returns the final value of the var i inside the loop or no value at all.但是,我正在努力在“点击”function 中传递数据,因为目前脚本只返回循环内 var i 的最终值或根本没有值。 Here's the code:这是代码:

 let heroStartingInventory = []; let heroStartingInventoryDescription = []; heroStartingInventory.push(itemList[0], itemList[2]); heroStartingInventoryDescription.push(itemListDescription[0], itemListDescription[2]); var i = 0; while(i < heroStartingInventory.length) { $('#chara-select-rightcol-content').append( '<div id="item-'+ i + '" class="button">'+ heroStartingInventory[i] +'</div>' ); $(' #item-'+i).on('click', function(){ new popupWindow(heroStartingInventory[i], heroStartingInventoryDescription[i]); }); i++; }

with this code popupWindow(heroStartingInventory[i], heroStartingInventoryDescription[i]);使用此代码 popupWindow(heroStartingInventory[i], heroStartingInventoryDescription[i]); shows no value.显示没有价值。 If I change it just for testing purpose in popupWindow(i, i);, each button just shows the last value of i (in this case 2) after the loop is broken.如果我只是为了在 popupWindow(i, i); 中进行测试而更改它,每个按钮只会在循环中断后显示 i 的最后一个值(在本例中为 2)。

Thank you for your time!感谢您的时间!

Yay, I just found the solution myself.是的,我自己找到了解决方案。 I took the code inside the loop in a separate function outside of it.我将循环内的代码放在一个单独的 function 之外。 Here's the code:这是代码:

 function test(index){ $('#chara-select-rightcol-content').append( '<div id="item-'+ index + '" class="button">&#9750; '+ heroStartingInventory[index] +'</div>' ); $(' #item-'+index).on('click', function(){ new popupWindow(heroStartingInventory[index], heroStartingInventoryDescription[index]); }); } while(i < heroStartingInventory.length) { test(i); i++; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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