分享

javascript-2个状态的带有舍入的舍入数字文本框

 印度阿三17 2019-10-26

我想要一个带有2种状态的html数字文本框,当聚焦时,它必须显示所有小数位,而当聚焦丢失时,仅显示2个小数.我几乎实现了.

HTML

<input data-bind="attr: { 'data-numericvalue': valueToRound}" class="numerictextbox"
       type="number"/>

Javascript:

var viewModel = {
    valueToRound: ko.observable(7.4267),
};

//NUMERIC TEXTBOX BEHAVIOUR
$('.numerictextbox').focusout(function () {
  $(this).attr("data-numericvalue", this.value); //this line does not update the viewModel
  this.value = parseFloat($(this).attr("data-numericvalue")).toFixed(2);
});
$('.numerictextbox').focusin(function () {
  if ($(this).attr("data-numericvalue") !== undefined) this.value = $(this).attr("data-numericvalue");
});

ko.applyBindings(viewModel); 

Jsfiddle:https:///7zzt3Lbf/64/

但是我的问题是,发生聚焦时,它不会更新绑定属性(在这种情况下为viewModel).这是我的代码的简化版本,因此我希望它对我的实际场景中的许多属性通用.

解决方法:

您混入了太多的jQuery 🙂

淘汰赛具有事件绑定和hasFocus绑定以处理UI输入.

在下面的示例中,我创建了一个视图模型,该模型具有可观察到的隐藏realValue,该值存储未修改的输入.当showDigits为false时,displayValue将此数字限制为2位数字.

我使用过hasFocus来跟踪我们是否要显示整数:它链接到showDigits.

var ViewModel = function() {
  this.showDigits = ko.observable(true);
  
  var realValue = ko.observable(6.32324261);

  this.displayValue = ko.computed({
    read: function() {
      return this.showDigits() 
        ? realValue()
        : parseFloat(realValue()).toFixed(2);
    },
    write: realValue
  }, this);
};


ko.applyBindings(new ViewModel()); 
<script src="https://cdnjs./ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<input data-bind="value: displayValue, hasFocus: showDigits" type="number"/>

编辑:在注释中,计算式的代码过多了:这是将计算式的逻辑包装在可重用的扩展器中的方法:

ko.extenders.digitInput = function(target, option) {
  var realValue = target,
      showRealValue = ko.observable(false),
      displayValue = ko.computed({
        read: function() {
          return showRealValue() 
            ? realValue()
            : parseFloat(realValue()).toFixed(2);
        },
        write: realValue
      }, this);
  
  displayValue.showRealValue = showRealValue;
  
  return displayValue;
};


var ViewModel = function() {
  this.value1 = ko.observable(6.452345).extend({ digitInput: true });
  this.value2 = ko.observable(4.145).extend({ digitInput: true });
};


ko.applyBindings(new ViewModel());
<script src="https://cdnjs./ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<input data-bind="value: value1, hasFocus: value1.showRealValue" type="number"/>
<input data-bind="value: value2, hasFocus: value2.showRealValue" type="number"/>
来源:https://www./content-1-522901.html

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多