时间微调器检查是否未定义不起作用

TimeSpinner Check If Undefined Not Working

本文关键字:是否 未定义 不起作用 检查 时间      更新时间:2023-09-26

目前我有一个输入文本字段,该字段可能有也可能没有与该特定元素绑定的时间转换器。在某些情况下,我需要完全删除 timespinner 功能(而不是禁用它(,以便在页面上正确显示它。

目前,我有代码来检查元素上是否存在 timepinner,如下所示:

if ($("#ElementOfInterest").timespinner !== undefined){
    $("#ElementOfInterest").timespinner("destroy");
}

这在首次加载页面时工作正常,但是,这会引发以下异常:

无法在初始化之前调用 TimesPinner 上的方法;已尝试 调用方法"销毁">

出于某种原因,对undefined的检查会通过并尝试对不存在的元素进行时间微调。

因此,我的 UI 目前正常运行的唯一方法是将其包装在如下所示的try/catch块中:

if ($("#ElementOfInterest").timespinner !== undefined) {
    try {
        $("#ElementOfInterest").timespinner("destroy");
    } catch (error) {
    }
}

这有效,但相当草率。我宁愿让检查成功并从代码中删除try/catch块。

我是否缺少一些特殊检查或其他东西?这是怎么回事?

更新

我尝试了@GlenSwift建议的以下代码:

if (typeof $("#ElementOfInterest").spinner("instance") !== 'undefined') {
    $("#ElementOfInterest").timespinner("destroy");
}

然而,这给了我这个例外:

无法在初始化之前调用微调器上的方法;尝试 调用方法"实例">

我也尝试了timespinner("instance")但我只是回来了:

未定义不是方法

因此,看起来没有实现检查timespinner的实例。

好吧,$("#ElementOfInterest").timespinner !== undefined只是检查是否定义了$().timespinner,只要加载插件,它就会定义。如何检查元素是否具有微调器添加的类。 if ($("#ElementOfInterest").hasClass('ui-spinner-input'))

尝试:

if (typeof $( "#ElementOfInterest" ).spinner( "instance" ) !== 'undefined') {
    $("#ElementOfInterest").timespinner("destroy");
}

参考: http://api.jqueryui.com/spinner/#method-instance