【问题标题】:Javascript push() method not working aside jQuery inArray()Javascript push() 方法在 jQuery inArray() 旁边不起作用
【发布时间】:2012-09-21 16:00:15
【问题描述】:

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

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

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

有效!

我无法弄清楚这里发生了什么,因为如果我手动进行其他测试,它也可以工作!

【问题讨论】:

  • 包含 HTML。我很确定这就是问题所在。
  • 如果您使用的是 XHTML 或 HTML5 之前的文档类型,则以数字开头的 ID 无效。

标签: javascript jquery arrays push


【解决方案1】:

试试这个 .. 而不是检查 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
         }   
    }
);

【讨论】:

    【解决方案2】:

    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

    正如我在问题 cmets 中所说,以数字开头的 ID 是非法的,除非您使用的是 HTML5 文档类型。

    【讨论】:

    • 我没有使用 var 因为它是一个全局变量
    • @GilbertoAlbino 然后在全局上下文中声明它。即使在那时,使用var 关键字也是一种很好的做法。如果没有任何 var 语句,您的代码将不会通过 JSHint/Lint,在严格模式下生成错误,并且 codeList 将被创建为不带 DontDelete 属性标志的窗口对象的属性。
    • 当然,如果您已经使用var 语句在全局上下文中声明了它,请忽略上面的注释。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-20
    • 1970-01-01
    • 2020-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-30
    相关资源
    最近更新 更多