2017-01-13 63 views
-2

我有這種情況,我需要在JavaScript函數中使用三個條件:條件。javascript中的多個「AND」條件

我已經寫了這樣的代碼

if ((frm_add_announcement.sublink[0].checked == true)) { 
    if ((document.getElementById('captionurl').value.trim() == "") && 
    (document.getElementById("captionfile").files.length == 0) && 
    (document.getElementById('ifpresent').value != "1")) { 
    alert("Enter a url/upload a file"); 
    //var alertmsg=document.getElementById("captionfile").value; 
    //alert(alertmsg); 
    document.getElementById('captionurl').focus(); 
    return false; 
    } 
    } 

但它不工作。有沒有控制檯錯誤

+1

它是否在控制檯中發生錯誤? –

+0

你應該逐一檢查每個條件。 –

+0

@ KeesvanLierop-No ..沒有錯誤。 – Vimal

回答

1

你的代碼是確定並沒有錯誤,但我看到,你可以通過創建變量,而不是做2個if語句做出重構,你能做的只有一個:

var captionurl = document.getElementById('captionurl'), 
    captionfile = document.getElementById('captionfile'), 
    ifpresent = document.getElementById('ifpresent'); 

if (frm_add_announcement.sublink[0].checked && 
    captionurl.value.trim() === '' && 
    captionfile.files.length === 0 && 
    ifpresent.value !== '1') { 
    alert('Enter a url/upload a file'); 
    //var alertmsg=captionfile.value; 
    //alert(alertmsg); 
    captionurl.focus(); 
    return false; 
} 

請注意,「但它不起作用」不表示什麼是預測結果

0

您的代碼看起來在語法上很好。如果您錯過了這部分,您需要在需要的地方撥打function。另一個可能的問題是,您可能需要檢查您的值是否在captionurl,文件數大於0且ifpresent值是1.在這種情況下,您需要有三個或以下條件:

if ((frm_add_announcement.sublink[0].checked == true)) { 
    if ((document.getElementById('captionurl').value.trim() == "") || 
     (document.getElementById("captionfile").files.length == 0) || 
     (document.getElementById('ifpresent').value != "1")) { 
     alert("Enter a url/upload a file"); 
     //var alertmsg=document.getElementById("captionfile").value; 
     //alert(alertmsg); 
     document.getElementById('captionurl').focus(); 
     return false; 
    } 
} 

你也可能想要否定你的第一個條件。