2017-02-20 68 views
0

我有一個jquery函數,我已經聲明瞭一個變量,並將其設置爲默認的false.and然後在If條件中,我爲該變量賦予了真值。但是我總是得到false.why是這樣嗎?當使用警告我得到「真正的」戰利品如果條件是「假」如何比較Javascript中的變量值?

這裏是我的代碼:

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))) { 
+0

如果可能的話給我們一個小提琴https://jsfiddle.net/ – Sarath

+0

你可以給一個例子鏈接來檢查實際發生的事情。所以我們可以幫忙? –

回答

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

false here 

ABC是這個裏面真實的,但它的這種功能的假外因爲你默認設置爲false ...這就是爲什麼你得到錯誤....如果你想真正的abc那麼你應該把你的「如果」條件內的上述功能

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的範圍相當不錯。

+0

我無法打開鏈接 –

+0

這裏是鏈接:https://youtu.be/SBwoFkRjZvE –

+0

也應該重構你的代碼。我會建議創建一個函數來將你的'if'語句放入'change'回調中,並調用該函數。您的函數在時間碼運行時的值將爲false。 –

0

當您更改輸入值時,將「abc」設置爲true,但當您僅設置「更改」功能時運行「if」條件,那時,您的「abc」僅設爲false。

,如果你希望你的「ABC」是真實的,移動的「如果」條件到.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 
    } 
}); 
+0

如果我移動我的條件裏面chage事件它不會工作。 –

+0

你有「MstCopyParseData [rowIndex] .ProductID == MstCopyParseData [parseInt(i)]。ProductID &&(i!= rowIndex &&(MstCopyParseData [i] .Product!=」「」之前abc == true,如果這條件是條件是錯誤的,並不意味着「abc」不是真的,也許這三個表達式中的一個是錯誤的。你可以寫if(abc == true)來判斷每個表達式以找出哪個表達式是錯誤的。 – Hejie

+0

如果(a && b)爲真,則表示a是真,b是真。 – Hejie