函数在文档就绪时无法正常工作

function not working properly when run on document ready

本文关键字:常工作 工作 文档 就绪 函数      更新时间:2023-09-26

>我有一个包含 2 个字段的表单:日期字段 #datefromtoday 和天数#daysfromtoday。我使用 javascript 函数来:

1)自动收听从今天开始的日期

,并(如果有日期)显示页面加载时从今天开始的天数

2)输入/修改天数时,从今天开始调整日期。

这是代码:

 $(document).ready(function (){
 function modifyDays(){ //definy function to modify days
    var endDateToDays = $( "#datefromtoday" ).val();
    var endDateToDays_obj = new Date(endDateToDays); // convert in object
    var endDateToDays_ms = endDateToDays_obj.getTime(); // convert in ms
    var todayDate = new Date(); //
    var todayDate_ms = todayDate.getTime(); //
    var daysFromToday =  parseInt(Math.ceil( (endDateToDays_ms - todayDate_ms) / 1000 / 60 / 60 / 24 ) ) || ''; //if not number display nothing

    document.getElementById("daysfromtoday").value = daysFromToday; //outuput
 }

    modifyDays(); //here is the problem. If I delete this line of code, everything works perfectly

    $("#datefromtoday").on('change', function(){ //run function when modify delay date
        modifyDays();       
    });
 });

问题

modifyDays 函数的工作方式类似于 on.change 事件上的超级按钮,但是当加载到文档就绪时,它会干扰数据表 www.datatables.net 以及其他脚本,并且它们不再工作......

我可能使用错误的代码在页面加载时调用该函数....有什么想法吗?感谢您的帮助!!

如果你认为是因为调用了 main 函数,在 html 页面的 body 元素中,添加一个 onload 属性:

<body onload="loaded()">

并声明加载为该主函数:

var loaded = function (){
   function modifyDays(){ //definy function to modify days
       var endDateToDays = $( "#datefromtoday" ).val();
       var endDateToDays_obj = new Date(endDateToDays); // convert in object
       var endDateToDays_ms = endDateToDays_obj.getTime(); // convert in ms
       var todayDate = new Date(); //
       var todayDate_ms = todayDate.getTime(); //
       var daysFromToday =  parseInt(Math.ceil( (endDateToDays_ms - todayDate_ms) / 1000 / 60 / 60 / 24 ) ) || ''; //if not number display nothing

       document.getElementById("daysfromtoday").value = daysFromToday; //outuput
   }

   modifyDays(); //here is the problem. If I delete this line of code, everything works perfectly

   $("#datefromtoday").on('change', function(){ //run function when modify delay date
       modifyDays();       
   });
};

那么如果问题是函数的调用方式,它应该可以工作。

我认为问题不是因为您在页面加载时调用该函数。错误可能来自函数 modifyDays 内部。我看到的唯一依赖性是 #datefromtoday 和 #daysfromtoday。检查当函数在 dom ready 事件上执行时,这些节点是否存在。

如果函数调用的计时有问题,您可以将modifyDays();调用放在window.setTimeout(modifyDays, 5000);或类似的东西中,以延迟它,直到其他脚本完成加载,这样这个代码段就不会中断或干扰它们。如果这有效,您可能希望在 html 中放置一个占位符

,以便在尚未加载时将其放在几秒钟内。