对象在循环中运行时未定义,但在按顺序执行时未定义

Object not defined when running in a loop, but not when executed sequentially

本文关键字:未定义 顺序 执行 运行时 对象 循环      更新时间:2024-06-13

我使用jQuery Masked Input插件将所有具有数据掩码属性的输入元素设置为属性掩码值:

给定这个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不是函数",表示没有定义"split"。

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

然而,这个代码运行得很好,掩码设置没有问题。

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

有人能揭露这种奇怪的行为吗?

演示jsFiddle此处

第二个由data() 键入为number

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

简单修复:

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

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

.data('mask')更改为.attr('data-mask')。出于某种原因,现在对我来说很好。。。也许jQuery版本相关?