【问题标题】:jquery: passing parameters and initial function to jquery prototypejquery:将参数和初始函数传递给 jquery 原型
【发布时间】:2016-10-12 21:36:26
【问题描述】:

我是这个网站的新手,也是 jQuery 的新手。

我想使用所谓的bootstrap material datetime picker,它允许您将插件分配给 HTML 输入元素。当此元素发生onfocus 事件时,选择器将唤醒并以覆盖模式显示在屏幕上。从选择器中选择日期后,选择器消失,HTML 变量的值被设置为选定的值。

我希望选择器在不与 HTML 输入变量交互的情况下显示;此外,用户应该能够在不使用选取器的情况下更改 HTML 输入元素的值。我的问题是我无法将初始参数和函数传递给插件。

插件一般是这样使用的:

$('#_Date_5').bootstrapMaterialDatePicker();  // this works

参数可以这样传递

$('#_Date_5').bootstrapMaterialDatePicker(
    {
        format: '<format>',
        shortTime: false,
        minDate: null,
        maxDate: null,
        currentDate: null,
        date: true,
        time: true,
        clearButton: true,
        nowButton: true,
        switchOnClick: false,
        triggerEvent: 'focus'
    } 
);

如果我想在插件初始化时调用一个函数(比如说_fireCalendar()),那么我可以使用以下代码:

$('#_Date_5').bootstrapMaterialDatePicker('_fireCalendar');

现在我正在使用一个临时 HTML 变量来为选择器提供所需的初始日期时间值,并将选择器绑定到这个临时变量。单击可编辑值右侧的标志性符号后,应显示选择器。现在用户可以在不使用选择器的情况下编辑值,或者决定使用选择器。

现在我的问题 - 是否可以在初始化时传递 both 一组参数 和 一个回调函数

我已经设法通过在插件的构造函数中调用_fireCalender() 来实现这一点,但是我希望能够在不修改插件本身的情况下做到这一点。

感谢您的帮助!

【问题讨论】:

    标签: javascript jquery parameters chaining


    【解决方案1】:

    好的 - 这是我的解决方案 - 讨厌(插件代码需要更改) - 但工作正常:

    1. 在插件的构造函数中添加了新参数 this.params.beforeHiding。参数 beforeHiding 初始设置为 null,可以设置为函数
    2. 在方法hide()末尾调用this.params.beforeHiding传递的函数

    在构造函数中

    this.params = {beforeHiding:null, <original parameters>}
    

    在hide()方法中

    if ( this.params.beforeHiding !== null ) this.params.beforeHiding();
    

    此代码将使用新功能:

    var date_interim = document.getElementById('var_interim');
    var date_original = document.getElementById('_Date_5');
    
    date_interim.value = date_original.value;
    
    $('#var_interim').bootstrapMaterialDatePicker(
    {
    format: '<format>',
    shortTime: false,
    date: true,
    time: false,
    clearButton: true,
    nowButton: true,
    switchOnClick: false,
    triggerEvent: 'focus',
    beforeHiding: function()
    {
    var date_interim = document.getElementById('var_interim');
    var date_original = document.getElementById('_Date_5');
    date_original.value = date_interim.value;
    }
    }
    );
    
    // display the picker by focussing it
    date_interim.focus();
    

    代码绑定到 HTML 图像标签的点击事件,并使用中间变量,这是一个 HTML 输入字段,用户既可以手动编辑原始值,也可以从选择器中选择一个值。聚焦临时变量会在屏幕上显示选择器。

    【讨论】:

      猜你喜欢
      • 2013-08-08
      • 2010-09-27
      • 1970-01-01
      • 2012-11-25
      • 2013-01-27
      • 2011-04-16
      • 2017-02-05
      • 2014-10-18
      • 1970-01-01
      相关资源
      最近更新 更多