将对象传递给事件 jQuery

Passing objects to events jQuery

本文关键字:事件 jQuery 对象      更新时间:2023-09-26

在此示例中,我尝试迭代传递给单击处理程序的对象的属性,但得到了意外的结果。这是小提琴

所以使用像这样的 JS 脚本

 $(document).ready(function ()
        {
            Label = function (name, toDate, fromDate)
            {
                this.name = name;
                this.toDate = toDate;
                this.fromDate = fromDate;
            }
            lbl = new Label('John', 'Today', 'Yesterday');

            $('#btnSubmit').click(function ()
            {
                for (var i in lbl)
                {
                    console.log(i);
                }
            });
            $('#btnSubmit2').click(function (Label)
            {
                for (var i in Label)
                {
                    console.log(i);
                }
            });
        });

为什么我不能在单击事件的函数中传递对象并迭代其属性,而不是像btnSubmit示例中那样使用 forin 循环?

回调始终以事件作为参数进行调用。编写click(function(Label){时,仅为该事件变量指定名称Label(从而隐藏外部构造函数)。

但是您可以访问外部作用域中定义的变量,因此您想要的可能是

var lbl = new Label('John', 'Today', 'Yesterday');
$('#btnSubmit').click(function(){
    for (var i in lbl) {
        console.log(i, lbl[i]); // for example "name", "John"
    }
});