Jquery:向Jquery原型传递参数和初始函数

jquery: passing parameters and initial function to jquery prototype

本文关键字:Jquery 函数 参数 原型      更新时间:2023-09-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变量向选择器提供所需的初始日期时间值,并将选择器绑定到这个临时变量。在可编辑值右侧单击图标符号后,应该显示选择器。现在,用户可以在不使用选择器的情况下编辑该值,或者决定使用选择器。

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

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

谢谢你的帮助!

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

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

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输入字段,用户既可以手动编辑原始值,也可以从选择器中选择一个值。聚焦临时变量会在屏幕上显示选择器。