构建一个在focusin/focusout上触发的函数



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

我的文档就绪函数在<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);

谢谢你的帮助!

您应该尝试:

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

activeblur不能工作吗?当有人点击输入时是活动的,当有人"点击"时是模糊的;取消选择";it

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

变量、范围和我构建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);

谢谢!

最新更新