【问题标题】:Firefox firing change event on input.attr("type", "number")Firefox 在 input.attr("type", "number") 上触发更改事件
【发布时间】:2017-12-19 05:12:15
【问题描述】:

我遇到了一个问题,仅在 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 上运行良好。

提前感谢您查看此内容!

【问题讨论】:

  • 由于影子 dom 处理数字输入的方式,这不是一个微不足道的变化。它失去焦点并不奇怪。改完后试试focus()就可以了
  • 您真的希望$ 是表单值的一部分吗?为什么要以这种方式解决它,而不是在包含 $ 的输入元素之前使用一个元素,然后以它们看起来像一个输入元素的方式设置这两个元素的样式?
  • 如果我调用focus(),它将无限重复。
  • 为了可读性,我想要更多来自 toLocaleString() 的,,因此是否有$ 并不会改变问题。

标签: javascript jquery firefox


【解决方案1】:

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

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"/>

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

【讨论】:

    猜你喜欢
    • 2011-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-21
    • 2021-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多