我正在尝试创建多个 div,每个 div 都有一个 mousedown 回调。
但是该回调函数不应该对所有 div 通用,它应该根据单击的 div 发挥不同的作用。
这是我用来生成 div 并设置回调的代码。
//some number
var num=4;
for(var z = 0 ; z < num ;z++)
{
//create a div with id 'z'
$("<div/>",{id:z}).appendTo("#empty");
//displaying the id on the screen
$("#"+z).text(z);
console.log("button "+z+" created");
//Callback function , which is not working as I want it to. See the bottom section for more details
$("#"+z).mousedown(function(){
console.log("Button "+z+" clicked !");
});
}
上面的代码运行如下...
单击任何一个 div 时,都会显示消息“已单击按钮 4!”在控制台中生成。
为了实现我的目标应该做什么?
最佳答案
最好为按钮使用一个类并为该元素创建回调。
var num=4;
for(var z = 0 ; z < num ;z++)
{
//create a div with id 'z'
$("<div/>",{id:z,class:'btn'}).appendTo("#empty");
//displaying the id on the screen
$("#"+z).text(z);
console.log("button "+z+" created");
}
$(".btn").mousedown(function(){
var z = $(this).attr('id');
console.log("Button "+z+" clicked !");
});
关于javascript - 如何动态创建不同的 mousedown 回调?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27977383/