jQuery技术:如何动态/响应更改jQuery datepicker的月数

我问这个问题是因为我找不到另一个问题的答案。 如果有,请链接到我。

我有一个jQuery Datepicker,我在其上设置参数numberOfMonths:2

如果screenSize低于某个数字(例如768px),我希望它为1。 我试过了:

$(window).resize(function(){ if($(window).width() < 768){ $('#datepicker').datepicker({ numberOfMonths: 1 }) } } 

但由于datepicker已经初始化,因此不起作用。

我能做什么?

    你走在正确的轨道上,但有足够的东西certificate是有帮助的,我想发表一个完整的答案。

    首先, 这是一个工作小提琴

    这是我提出的代码,其中的注释解释了每个元素:

     // "No-conflict" jQuery document ready, to ensure doesn't collide with other libraries jQuery(function($) { // The initial datepicker load $('#datepicker').datepicker({ numberOfMonths: 3 }); // We're going to "debounce" the resize, to prevent the datePicker // from being called a thousand times. This will help performance // and ensure the datepicker change is only called once (ideally) // when the resize is OVER var debounce; // Your window resize function $(window).resize(function() { // Clear the last timeout we set up. clearTimeout(debounce); // Your if statement if ($(window).width() < 768) { // Assign the debounce to a small timeout to "wait" until resize is over debounce = setTimeout(function() { // Here we're calling with the number of months you want - 1 debounceDatepicker(1); }, 250); // Presumably you want it to go BACK to 2 or 3 months if big enough // So set up an "else" condition } else { debounce = setTimeout(function() { // Here we're calling with the number of months you want - 3? debounceDatepicker(3) }, 250); } // To be sure it's the right size on load, chain a "trigger" to the // window resize to cause the above code to run onload }).trigger('resize'); // our function we call to resize the datepicker function debounceDatepicker(no) { $("#datepicker").datepicker("option", "numberOfMonths", no); } }); 

    如果您不熟悉“去抖动”的概念, 请参阅此文章 。 这个概念是您阻止代码在事件的每个单个实例上运行。 在这种情况下,500像素的大小调整可能会触发“resize”事件数百次,如果我们没有“去抖动”,则会调用datepicker函数数百次。 显然我们并不关心对datepicker的所有“临时”调用,我们真的只关心最后一个调用,它是由最后一个resize事件触发的,它应该反映用户停止的最终大小。

    如果已经初始化了datepicker,则应该使用选项setters:

     $( "#datepicker" ).datepicker( "option", "numberOfMonths", [ 2, 3 ] ); 

    参数也可以是数字,就像初始化它一样。 查看链接以获取更多信息。

    需要了解更多jQuery教程分享如何动态/响应更改jQuery datepicker的月数,都可以关注jQuery技术分享栏目---计算机技术网(www.ctvol.com)!

      以上就是jQuery教程分享如何动态/响应更改jQuery datepicker的月数相关内容,想了解更多jQuery开发(异常处理)及jQuery教程关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/jquerytutorial/982063.html

      (0)
      上一篇 2021年12月13日
      下一篇 2021年12月13日

      精彩推荐