所以我尝试了这样一个最简单的情况(使用this 表示maskedinput.js,但请注意我在下面编辑它,this 表示jquery-1.11.2.js):
<html>
<body>
<script type="text/javascript" src="./jquery-1.11.2.js"></script>
<script type="text/javascript" src="./jquery.maskedinput.js"></script>
<script type="text/javascript">
jQuery(function($) {
$.mask.definitions['~']='[+-]';
$("#tin").mask("99-9999999",{completed:function(){alert("Now you typed: "+this.val());}});
});
</script>
<table border="0">
<tbody>
<tr>
<td>Tax ID</td>
<td><input type="text" tabindex="5" id="tin"></td>
<td>99-9999999</td>
</tr>
</tbody>
</table>
</body>
</html>
我对 maskedinput 源进行了一些编辑,以查看东西何时以及从何处触发。 I'll paste.ee it here,但这里是主要部分...
- 查找
.on("blur.mask")... 行
- 请注意,它对
blur、keydown、input 和paste 重复使用相同的函数。
- 添加
console.log 以告诉您每次调试粘贴时触发的特定事件。
这是我所做的(请注意,如果您使用的是 IE8-,则需要“保护”console.log 调用或在打开开发工具的情况下运行它):
}).on("blur.mask", blurEvent).on("keydown.mask", keydownEvent).on("keypress.mask", keypressEvent).on("input.mask", function() {
console.log("mask called: " + arguments[0].type); // <<< New debugging line.
input.prop("readonly") || setTimeout(function() {
var pos = checkVal(!0);
input.caret(pos);
tryFireCompleted("mask");
}, 0);
}), chrome && android && input.off("input.mask").on("input.mask", androidInputEvent),
当您粘贴内容时,会为“相同”操作调用两个事件处理程序。
mask called: paste
mask called: input
它们最终都调用了tryFireCompleted,它触发了我们在上面我们自己的代码行中设置的.completed函数:
$("#tin").mask("99-9999999",{completed:function(){alert("Now you typed: "+this.val());}});
如果您删除 paste.mask 事件处理程序,该问题就会消失。这是关键部分:
.on("input.mask paste.mask",
...更改为...
.on("input.mask",
...所以paste.mask 消失了。 (当然,在发布到生产环境之前,请删除 console.log 行。)
现在这可能完全独立。粘贴正在发射input,因此拥有paste 也可能是矫枉过正。但在将其用作永久修复之前,我会进行更多检查。我确实尝试过用鼠标右键单击粘贴,这个更改很好。不确定paste 何时被解雇而input 不是。
如果存在 一个边缘情况,即调用了 paste 而没有调用 input(或者你真的希望 tryFireCompleted 触发两次),你需要想办法用更复杂的代码抑制第二个tryFireCompleted。
但是,如果没有completed 函数,我认为两次触发不会是一个明显的问题,这就解释了为什么这可能会被忽略。很好的发现。