简体   繁体   English

将参数传递给javascript函数时获取[object]

[英]Getting [object] when passing parameter to javascript function

I have the following function that takes three arguments. 我有以下带有三个参数的函数。

initializeDateDropdown("year", "month", "day");

    function initializeDateDropdown(year1,month1,day1) {
        var currentYear = new Date().getFullYear();
        $("#"+year1).append(function () {
            var yearList = '';
            for (var i = 1951; i <= currentYear; i++) {
                yearList += '<option value="' + i + '">' + i + '</option>';
            }
            return yearList;
        }).val(currentYear)
      .add($('#'+month1).val(new Date().getMonth()))
      .bind('change', showDays);

        showDays(year1, month1, day1);

        $('#'+day1).val(new Date().getDate());


    }

In the definition of the showDays() method, when I try to display the year1, I keep getting [object] [object] and month1 and day1 as undefined . showDays()方法的定义中,当我尝试显示year1时,我不断获得[object] [object]以及month1和day1为undefined

Can anybody tell me what is wrong with this code? 谁能告诉我这段代码有什么问题吗?

Below is the showDays method defination. 下面是showDays方法的定义。

function showDays(year, month, day) {
        alert(year);
        var days = new Date($("#" + year).val(), parseInt($('#' + month).val(), 10) + 1, 0).getDate();

        var prevSelectedDate = $('#' + day).val();
        $('#' + day).empty();
        for (var i = 1; i <= parseInt(days, 10) ; i++) {
            $('#' + day).append($('<option />', { text: i, value: i }));
        }

        $('#' + day).val(prevSelectedDate);
    }

Please help me with this. 请帮我解决一下这个。

When you do .bind('change', showDays) , this is the equivalent: 当您执行.bind('change', showDays) ,这等效于:

.bind('change', showDays(event));

Where event is the event object . 其中event事件对象

You'll need to change that part of the function to: 您需要将函数的该部分更改为:

.bind('change', function(){
    showDays(year1, month1, day1);
});

Since you need to pass parameters to the function ( year1 , month1 , day1 ), you need to wrap it in an anonymous callback function. 由于您需要将参数传递给函数( year1month1day1 ),因此需要将其包装在匿名回调函数中。

On a secondary note, .bind is deprecated . 在第二个注释中, 不赞成使用.bind Use .on() : 使用.on()

.on('change', function(){
    showDays(year1, month1, day1);
});

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

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