如何在Javascript中比较变量值?

时间:2017-02-20 05:36:29

标签: javascript jquery

我有一个jquery函数,其中我声明了一个变量并使其默认为false。然后在If条件中我为该变量赋值true。但我总是得到假..为什么会这样? ?当使用警报时我得到'真'但在if条件下它是'假'

这是我的代码:

var abc = false
$('#dataTable tr td').find("input[name='" + 'lstDetlIssue[' + i + '].Product' + "']").change(function () {
abc = true;
alert(abc);
});

if (MstCopyParseData[rowIndex].ProductID == MstCopyParseData[parseInt(i)].ProductID && (i != rowIndex && (MstCopyParseData[i].Product != "" && abc == true ))) {

3 个答案:

答案 0 :(得分:1)

    $('#dataTable tr td').find("input[name='" + 'lstDetlIssue[' + i + '].Product' + "']").change(function () {
    abc = true;
    alert(abc); // true here
    });

false here

ABC在这个内部是真的,但是在这个函数之外它是假的,因为你默认将它设置为假...这就是为什么你会变错...如果你想为abc真的那么你应该把你的“如果“上述功能内部的条件

答案 1 :(得分:0)

这可能是范围界定的问题。从您给出的代码中很难说出来但是尝试做这样的事情:

// create a variable that refers to the scope you want.
const that = this;
let abc = false;

$('#dataTable tr td').find("input[name='" + 'lstDetlIssue[' + i + '].Product' + "']").change(function () {
    // then change it like so
    that.abc = true;
    alert(that.abc);
});

This youtube video很好地解释了javascript范围。

答案 2 :(得分:0)

当您更改输入值时,将“abc”设置为true,但是当您设置“更改”功能时,“if”条件会运行,此时,您的“abc”只会设置为false。

如果您希望“abc”为true,请将“if”条件移动到.change()

var abc = false
$('#dataTable tr td').find("input[name='" + 'lstDetlIssue[' + i + '].Product' + "']").change(function () {
  abc = true;
  alert(abc);
  if (MstCopyParseData[rowIndex].ProductID == MstCopyParseData[parseInt(i)].ProductID && (i != rowIndex && (MstCopyParseData[i].Product != "" && abc == true ))){
    //TODO
  }
});