Javascript push()方法无法使用jQuery inArray()

时间:2012-09-21 16:00:16

标签: javascript jquery arrays push

我正在尝试将值添加到一个简单的数组中,但我无法将值推送到数组中。

到目前为止一切顺利,这是我的代码:

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
         }   
    }
);

有效!

我无法弄清楚这里发生了什么,因为如果我手动进行其他测试也会有效!

2 个答案:

答案 0 :(得分:4)

尝试这个..而不是检查bool检查其索引.. 它找不到时返回-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
         }   
    }
);

答案 1 :(得分:3)

当找不到值时,

jQuery.inArray会返回-1,而jQuery 1.7+上也会弃用.live,并且var中缺少codeList语句}} 宣言。这是对代码的重写:

//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是非法的。