2014-03-12 29 views
0

我收到此錯誤信息:未捕獲的ReferenceError:無效的左手側分配中的if語句

Uncaught ReferenceError: Invalid left-hand side in assignment script.js:37 visaType script.js:37 (anonymous function)

這是代碼:

的script.js:

function visaType() { 
    var visaOld = $('#inputVisaOld').val(); 
    var visaNew = $('#inputVisaNew').val(); 

    if (visaOld = 'Studying Mandarin Chinese' && visaNew = 'Foreign Student') { 
     // the error message points here 
     return '<div class="alert alert-info" Documents for FR -> FS</div>'; 
    } else if (visaOld = 'Tourism' && visaNew = 'Joining Taiwananese Family') { 
     return '<div class="alert alert-info" Documents for P -> TS</div>'; 
    } else { 
     return '<div class="alert alert-error>Not allowed to change</div>'; 
    } 
    } 

html:

<div class="form-group"> 
     <label for="inputVisa">Current Visa <span class="text-muted">(Optional)</span></label> 
     <input type="text" class="form-control" id="inputVisaOld" placeholder="Enter Current Visa"> 
    </div> 
    <div class="form-group"> 
     <label for="inputVisa">New Visa</label> 
     <input type="text" class="form-control" id="inputVisaNew" placeholder="Enter Visa to Apply"> 
    </div> 

可能是什麼問題?

回答

2

visaOld = 'Studying Mandarin Chinese'具有單一=標誌,這意味着你的時候,你應該比較分配:visaOld === 'Studying Mandarin Chinese'

這是在幾個點,而不僅僅是一個。

1

Javascript中的比較運算符是==而不是=。所以它應該是:

if (visaOld == 'Studying Mandarin Chinese' && visaNew == 'Foreign Student') { 
    // the error message points here 
    return '<div class="alert alert-info" Documents for FR -> FS</div>'; 
} else if (visaOld == 'Tourism' && visaNew == 'Joining Taiwananese Family') { 
    return '<div class="alert alert-info" Documents for P -> TS</div>'; 
} else { 
    return '<div class="alert alert-error>Not allowed to change</div>'; 
} 

=是用於變量賦值。

+0

@phenomnomnominal這些比較沒有必要使用'==='。 – Barmar

+1

兩個原因如何:可維護性和意圖的清晰度?顯然,在這裏你不會*使用'===',但一般認爲最好這樣做。 – phenomnomnominal

+1

這是你的風格,不要強加給別人。如果您想評論,請這樣做,但不要編輯他人的答案。 – Barmar

1

編程中最古老的錯誤之一。你的任務應該是比較。使用==而不是=,它會起作用。

爲什麼當前的代碼有語法錯誤:

分配(=)來&&後運算符優先級。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence所以你的發言被評價像以下

if (visaOld = ('Studying Mandarin Chinese' && visaNew) = 'Foreign Student') { 

使用括號強迫你要

if ((visaOld = 'Studying Mandarin Chinese') && (visaNew = 'Foreign Student')) { 

什麼,但請記住,分配內的,如果是不推薦的語句,也並非您的本意。

相關問題