为什么我的 jquery 插件中的 .change() 函数不起作用?

Why is my .change() function inside jquery plugin is not working?

我正在尝试制作一个简单的年龄计算器。它只是在输入端添加年龄。它计算日期选择器输入的年龄。 .split 不是很干净,只是更改日期格式。

我猜我的问题是范围问题。

我想要的是我的插件,可以根据输入的变化更新年龄。这是:

 (function ($) {
        $.fn.ageIt = function () {
            var that = this;
            var positonthat = $(that).position();
            var sizethat = $(that).width();

            //Add div for ages
            var option = {
                "position": " relative",
                "top": "0",
                "left": "300"
            };

            var templateage = "<div class='whatage" + $(this).attr('id') + "' style='display:inline-block;'>blablabla</div>";
            $(that).after(templateage);
            var leftposition = (parseInt(sizethat) + parseInt(positonthat.left) + parseInt(option.left));
            var toposition = parseInt(positonthat.top) + parseInt(option.top);

            $('.whatage' + $(this).attr("id")).css(
                {
                    position: 'absolute',
                    top: toposition + "px",
                    left: leftposition + "px",
                    "z-index": 1000,
                }

                ); 

            //uptadateage
            function updateage(myobj) {
                var formateddate = myobj.val().split(/\//);
                formateddate = [formateddate[1], formateddate[0], formateddate[2]].join('/');
                var birthdate = new Date(formateddate);
                var age = calculateAge(birthdate);
                $('.whatage' + $(myobj).attr("id")).text(age + "&nbsp;ans");

            };

            //updateage($(this));
            $(this).on("change", updateage($(this)));

            //
        }
    })(jQuery);

    function calculateAge(birthday) {
        var ageDifMs = Date.now() - birthday.getTime();
        var ageDate = new Date(ageDifMs); // miliseconds from epoch        
        return Math.abs(ageDate.getUTCFullYear() - 1970);
    }

    $("#BirthDate").ageIt();

这一行:

        $(this).on("change", updateage($(this)));

表示,“将 'change' 事件的处理程序设置为 使用参数 $(this) 调用函数 updateage() 的结果。那是一个函数调用,因为你已经在变量that中捕获了this的值,所以你可以这样写updateage(),这样它就不需要参数了:

        function updateage() {
            var formateddate = that.val().split(/\//);
            formateddate = [formateddate[1], formateddate[0], formateddate[2]].join('/');
            var birthdate = new Date(formateddate);
            var age = calculateAge(birthdate);
            $('.whatage' + $(that).attr("id")).text(age + "&nbsp;ans");

        };

然后设置事件处理程序:

    $(this).on("change", updateage);

请注意,在您正在构建的 jQuery 附加组件中,this 的值将是调用该方法的 jQuery 对象。您不需要创建新的 jQuery 对象($(this)$(that))。所以只写:

    this.on("change", updateage);