2012-09-21 39 views
3

我想將值添加到一個簡單的數組,但我無法將值推入到數組中。JavaScript推()方法不工作jQuery inArray()

到目前爲止好,這是我的代碼有:

codeList = []; 

jQuery('a').live(
    'click', 
    function() 
    { 
     var code = jQuery(this).attr('id'); 
     if(!jQuery.inArray(code, codeList)) { 
       codeList.push(code); 
       // some specific operation in the application 
     } 
    } 
); 

上面的代碼不工作! 但是,如果我手動傳遞值:

codeList = []; 

jQuery('a').live(
    'click', 
    function() 
    { 
     var code = '123456-001'; // CHANGES HERE 
     if(!jQuery.inArray(code, codeList)) { 
       codeList.push(code); 
       // some specific operation in the application 
     } 
    } 
); 

它的工作原理!

我不知道這裏發生了什麼,因爲如果我手動進行其他測試,它也可以工作!

+1

包含HTML。我確信這是問題所在。 – iambriansreed

+3

如果您在HTML5之前使用XHTML或doctype,則以數字開頭的ID無效。 –

回答

4

試試這個..相反cheking爲布爾檢查其索引的.. 它返回-1,當找不到它..

var codeList = []; 

jQuery('a').live(
    'click', 
    function() 
    { 
     var code = '123456-001'; // CHANGES HERE 
     if(jQuery.inArray(code, codeList) < 0) { // -ve Index means not in Array 
       codeList.push(code); 
       // some specific operation in the application 
     } 
    } 
); 
+0

你的解決方案就像一個魅力! –

3

jQuery.inArray返回-1時未找到該值,也.live在jQuery 1.7+上已棄用,並且您在codeList聲明中缺少var聲明。這是你的代碼的改寫:

//without `var`, codeList becomes a property of the window object 
var codeList = []; 

//attach the handler to a closer ancestor preferably 
$(document).on('click', 'a', function() { 
    //no need for attributes if your ID is valid, use the element's property 
    var code = this.id; 
    if ($.inArray(code, codeList) === -1) { //not in array 
     codeList.push(code); 
    } 
}); 

Fiddle

正如我在這個問題評論說,除非你使用HTML5文檔類型以數字開頭的ID是非法的。

+0

我沒有使用var,因爲它是一個全局變量 –

+0

@GilbertoAlbino然後在全局上下文中聲明它。儘管如此,最好使用'var'關鍵字。沒有任何'var'語句,你的代碼將不會通過JSHint/Lint,在嚴格模式下產生錯誤,並且'codeList'將被創建爲窗口對象的屬性而沒有DontDelete屬性標誌。 –

+0

當然,如果您已經在全局上下文中用'var'語句聲明瞭它,請忽略上面的註釋。 –