我有这个代码比较两个值来验证它们是否相同:
$(document).on("blur", "[id$=boxSection5Total]", function (e) {
var totalvalue = $(this).val();
var paymenttotalvalue = $('[id$=boxPaymentAmount]').val();
if (totalvalue != paymenttotalvalue) {
console.log("The value in 'Total' does not equal the previous value in 'Payment Total.'");
alert("The value in 'Total' does NOT equal the previous value in 'Payment Total.' payment total is " + paymenttotalvalue + " and total is " + totalvalue);
}
else {
console.log("The value in 'Total' DOES equal the previous value in 'Payment Total'");
}
});
但是,如果两个文本元素都留空,则会失败 - 它们被认为不相等(“if(totalvalue!= paymenttotalvalue)”条件为真)。
如何重构代码,以便忽略两个元素都留空的情况?
类似的东西:
$(document).on("blur", "[id$=boxSection5Total]", function (e) {
var totalvalue = $(this).val();
var paymenttotalvalue = $('[id$=boxPaymentAmount]').val();
if ((totalvalue == null) & (paymenttotalvalue == null)) {
return;
}
. . .
});
“boxSection5Total”和“boxPaymentAmount”都是文本元素(文本框)。
答案 0 :(得分:2)
如果这些实际上是空白文本值,那么使用....
if(totalvalue === "" && paymenttotalvalue === "")
{
return;
}
或(我认为)
if(totalvalue == 1 && paymenttotalvalue == 1)
{
return;
}
答案 1 :(得分:2)
如果你想特别检查null,你应该尝试这样的事情。
if (totalvalue !== null && paymenttotalvalue !== null && totalvalue != paymenttotalvalue)
如果你想检查untruthy(也见这里:JavaScript: how to test if a variable is not NULL)你可以使用这个:
if (totalvalue && paymenttotalvalue && totalvalue != paymenttotalvalue)