繁体   English   中英

Firefox在input.attr(“ type”,“ number”)上触发更改事件

[英]Firefox firing change event on input.attr(“type”, “number”)

我遇到一个问题,仅在firefox中,当输入被聚焦时,我将输入类型从"text"更改为"number" ,触发了更改事件,并且输入失去了焦点。

我要实现的是将输入更改为焦点上的数字字段,允许进行编辑,并在模糊时将输入更改为LocaleString()。

这是我的代码:

 $("input").focusin(function() { $(this).val(toNumber($(this).val())); $(this).attr("type", "number"); }); $("input").focusout(function() { $(this).attr("type", "text"); $(this).val("$ " + toCost($(this).val())); }); // Added during edit to make code testable $('input').on('change', function(){ console.log('changed'); }) function parseNumber(value) { var result = parseFloat(toNumber(value)); if (!isNaN(result)) { return result; } return 0; } function toNumber(str) { return str.replace(/\\s/g, "").replace(/\\$/g, "").replace(/,/g, ""); } function toCost(number) { return parseNumber(number).toLocaleString(); } 
 <!-- Added during edit to make code testable --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <input/> 

我不知道为什么在Firefox中选择输入时会触发更改事件并失去焦点。 当我尝试在控制台上使用$("#myInput").focusin()时,它会按照我想要的方式工作。

它可以在Chrome和Microsoft Edge上正常运行。

在此先感谢您看一下!

我目前正在使用它作为解决方案:

 function is_firefox() { return navigator.userAgent.search("Firefox") >= 0; } $("input").focusin(onFocusIn); $("input").focusout(onFocusOut); $('input').change(onInputChange); function onFocusIn() { $(this).val(toNumber($(this).val())); $(this).attr("type", "number"); // remove on 'change' and 'focusout', and add back after a short delay if (is_firefox()) { $(this).off("change"); $(this).off("focusout"); setTimeout(function(element){ element.change(onInputChange); element.focusout(onFocusOut); }, 15, $(this)); } } function onFocusOut() { $(this).attr("type", "text"); $(this).val("$ " + toCost($(this).val())); } function onInputChange() { console.log("changed"); } $("input").focusout(); function parseNumber(value) { var result = parseFloat(toNumber(value)); if (!isNaN(result)) { return result; } return 0; } function toNumber(str) { return str.replace(/\\s/g, "").replace(/\\$/g, "").replace(/,/g, ""); } function toCost(number) { return parseNumber(number).toLocaleString(); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <input value="1000"/> 

我认为这不是完美的解决方案,但现在对我有用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM