簡體   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