0

我正在尝试构建一个函数,该函数将触发 focusin / focusout 并<span>在我在输入字段中输入数据时显示结果。

我的 doc-ready 函数在.<head>之后的脚本标记中调用下面的代码<body>

这是一个屏幕截图: 这是输入字段和显示结果的跨度

代码:

var $costPrice = parseInt($("#cost-price").val()); // Cost price <div>
var $markupPercentage = parseInt($("#markup-percentage").val()); // Markup <div>

var $sellingPrice = ($markupPercentage / 100) * $costPrice + $costPrice;

var $finalPrice = $("#final-price"); // This <span> tag that receive the result of $sellingPrice

function showPrice($sellingPrice, $finalPrice){
    if ($sellingPrice !== null) {
        $finalPrice.html("$" + $sellingPrice);
    } else {
        $finalPrice.html("$0"); // Here I want to replace Nan by $0
    }
};

$costPrice.focusout(showPrice); // I want to trigger/show the result.
$markupPercentage.focusout(showPrice); // I want to trigger/show the result.

如果我在输入中输入一个值并在控制台中运行下面的代码,它就可以工作。但这不是交互式的。我想获得相同的结果,但在 focusin / focusout 输入字段上。

var $costPrice = parseInt($("#cost-price").val()); // Cost price <div>
var $markupPercentage = parseInt($("#markup-percentage").val()); // Markup <div>

var $sellingPrice = ($markupPercentage / 100) * $costPrice + $costPrice;

var $finalPrice = $("#final-price").html("$" + $sellingPrice);

感谢帮助 !

4

3 回答 3

0

你应该试试:

$("#cost-price").focusout(function(){
//do something
});

$("#final-price").focusout(function(){
//do something
});
于 2020-12-08T02:23:05.017 回答
0

不会activeblur 工作?活跃将是当有人点击输入时,当有人“取消选择”它时会变得模糊

于 2020-12-08T10:51:42.100 回答
0

最后,我自己找到了解决方案。

变量、范围和我构建的方式function sellingPrice是主要问题。

然后,当我在输入字段中键入数据时,我使用.on()方法而不是.focusout()方法.focusin()来输出结果。

代码:

var $costPrice;
var $markupPercentage;
var $sellingPrice;

function sellingPrice($costPrice, $markupPercentage, $sellingPrice) {
    
  $costPrice = parseInt($("#cost-price").val() || 0);
  $markupPercentage = parseInt($("#markup-percentage").val() || 0);

  $sellingPrice = ($markupPercentage / 100) * $costPrice + $costPrice;

  $("#final-price").html("$" + $sellingPrice || 0);
}

$("#cost-price").on('input', sellingPrice);
$("#markup-percentage").on('input', sellingPrice);

谢谢!

于 2020-12-08T18:59:57.297 回答