javascript - 如何动态创建不同的 mousedown 回调?

标签 javascript jquery html css mousedown

我正在尝试创建多个 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 !");
        });
    }

上面的代码运行如下...

output

单击任何一个 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/

相关文章:

javascript - 多词预测/自动完成文本区域?

javascript - Rails - jQuery 不适用于 Heroku 的生产环境

javascript - 如何获得 HTML5 的 window.fileReader API 的跨浏览器兼容性

javascript - 如何在 Javascript 中检查 object 或 var 是否可遍历?

javascript - 将 Carrage 返回转换为 br 标签

javascript - 如何在 python 中使用 selenium 驱动程序单击链接而不知道 anchor 标记内的文本

javascript - jquery 中的字符串比较 find() 不适用于 <

javascript - 无法将串联值附加到 div block 中的 customId

html - golang Beego中如何解析表单数组

html - flex 订单不适用于无序列表