javascript - Firefox 在 input.attr ("type"、 "number"上触发更改事件

标签 javascript jquery firefox

我遇到了一个问题,仅在 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"/>

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

关于javascript - Firefox 在 input.attr ("type"、 "number"上触发更改事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47880363/

相关文章:

jquery - 使用 jquery 添加的 MS 过滤器

javascript - 字符串上下文中的新日期在 Firefox 中不起作用

javascript - React 未在子组件中显示更新状态

javascript - sessionScope HashMap 和复选框

javascript - 如何水平翻转 Three.js 纹理

javascript - 检查 Firefox 扩展中是否存在首选项

html - Firefox 无法正确显示 CSS header

javascript - 创建 JQuery div 类过滤器不起作用

javascript - ChartJS 2.6 - 条形图固定高度可滚动-X

javascript - Highcharts 图像渲染器自动高度