gpt4 book ai didi

javascript - KnockOut 货币绑定(bind)处理程序

转载 作者:行者123 更新时间:2023-12-02 13:46:53 25 4
gpt4 key购买 nike

我正在尝试创建一个绑定(bind)处理程序来显示给定格式的货币空间。但是当我想使用该值时,它必须再次 float 。

例如我想要的是;

money = ko.observable();

给定:

钱(1500000.75);

显示:1.500.000,75

像这样。

我用过;

ko.bindingHandlers.numericValue = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
ko.utils.registerEventHandler(element, 'change', function (event) {
var observable = valueAccessor();
var positions = ko.utils.unwrapObservable(allBindingsAccessor().positions) || ko.bindingHandlers.numericValue.defaultPositions;

if (ko.utils.unwrapObservable(allBindingsAccessor().positions) == 0) {
positions = 0;
}

if (isNaN(parseFloat($(element).val())))
observable(0);
else {
if (!ko.utils.unwrapObservable(allBindingsAccessor().noDecimalPoints))
observable(parseFloat($(element).val().replace(".", "").replace(",", ".")).toFixed(positions).replace(",", "."));
else
observable(parseFloat($(element).val().replace(".", "").replace(",", ".")).toFixed(positions));
}
});
},
update: function (element, valueAccessor, allBindingsAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
if (value != null) {
var positions = ko.utils.unwrapObservable(allBindingsAccessor().positions) || ko.bindingHandlers.numericValue.defaultPositions;
if (ko.utils.unwrapObservable(allBindingsAccessor().positions) == 0) {
positions = 0;
}
var formattedValue = parseFloat(value).toFixed(positions);
var finalFormatted = formattedValue;
if (!ko.utils.unwrapObservable(allBindingsAccessor().noDecimalPoints))
finalFormatted = ko.bindingHandlers.numericValue.withCommas(formattedValue);
ko.bindingHandlers.value.update(element, function () { return finalFormatted; });
}
},
defaultPositions: 2,
noDecimalPoints: false,
withCommas: function (original) {
original += '';
x = original.split('.');
x1 = x[0];
x2 = x.length > 1 ? ',' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + '.' + '$2');
}
return x1 + x2;
}
};

作为绑定(bind)并且

  <input class="actTextBox" placeholder="" data-bind="numericValue: money">

作为 html。但是当我输入“1500000.43”时,我什么也没看到。我看到空格。

我找不到任何答案。

最佳答案

试试这个:

ko.bindingHandlers.currency = {
update: function(element, valueAccessor){
// retrieve observable value
var value = ko.utils.unwrapObservable(valueAccessor()) || 0;
//convert to number of string
value = + value;
//format currency
var formattedText = "$" + value.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,");
//apply formatted text to the underlying DOM element
$(element).text(formattedText);
}
};

关于javascript - KnockOut 货币绑定(bind)处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41330205/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com