【问题标题】:Object not defined when running in a loop, but not when executed sequentially在循环中运行时未定义对象,但在顺序执行时未定义
【发布时间】:2015-02-26 16:08:26
【问题描述】:

我正在使用jQuery Masked Input plugin 设置所有输入元素,其中数据掩码属性定义为属性掩码值:

鉴于此 html:

<input type='text' id="a" data-mask='999?999' />
<input type='text' id="b" data-mask='999' />

还有这个脚本:

$("input[data-mask]").each(function() {

    var maskValue = $(this).data('mask');

    console.log($(this).attr('id') + ": " + maskValue);

    //undefined error here on second iteration "b: 999"
    //no issues if you remove the data-mask from one of the input elements
    return $(this).mask(maskValue);

});

第二次迭代抛出一个错误:“Uncaught TypeError: undefined is not a function”在这一行,说'split'没有定义。

firstNonMaskPos = null, $.each(mask.split(""), function(i, c) {

然而,这段代码工作得很好,掩码设置没有问题。

$('#a').mask('999?999');
$('#b').mask('999');

有人能对这种奇怪的行为有所了解吗?

Demo jsFiddle here

【问题讨论】:

    标签: javascript jquery maskedinput


    【解决方案1】:

    第二个被data()输入为number

    由于 split() 是一个字符串方法,它会抛出错误。

    简单修复:

    var maskValue = "" + $(this).data('mask');
    

     var maskValue =  $(this).data('mask').toString();
    

    【讨论】:

      【解决方案2】:

      .data('mask') 更改为.attr('data-mask')。出于某种原因,现在对我来说可以正常工作...也许与 jQuery 版本有关?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-01-30
        • 2019-06-04
        • 2012-03-16
        • 2019-01-07
        • 1970-01-01
        • 2021-04-14
        相关资源
        最近更新 更多