如何忽略 jQuery 中的两个空值或未分配的值?

How can I ignore two null or unassigned values in jQuery?

我有这段代码可以比较两个值以验证它们是否相同:

$(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" 都是文本元素(文本框)。

如果这些实际上是空白文本值,则使用....

if(totalvalue === "" && paymenttotalvalue === "")
{
    return;
}

或(我认为)

if(totalvalue == 1 && paymenttotalvalue == 1)
{
    return;
}

如果你想专门检查 null 你应该尝试这样的事情。

if (totalvalue !== null && paymenttotalvalue !== null && totalvalue != paymenttotalvalue)

如果你想检查不真实的(另见这里:JavaScript: how to test if a variable is not NULL)你可以使用这个:

if (totalvalue && paymenttotalvalue && totalvalue != paymenttotalvalue)