2012-09-21 101 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'语句声明了它,请忽略上面的注释。 –