gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 18:29:43 25 4
gpt4 key购买 nike

我正在尝试制作一个简单的年龄计算器。它只是在输入的一侧添加年龄。它计算日期选择器输入中的年龄。.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);

关于javascript - 为什么我的 .change() 函数在 jquery 插件中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38328835/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com