【问题标题】:jQuery.inArray returning -1jQuery.inArray 返回 -1
【发布时间】:2014-09-26 01:25:01
【问题描述】:

我写了这段代码:

    $(document).on('click','.remove_email',function(event) {
        dato_in_mod=(($(event.target).text()).replace(" ",""));
        mail_address.splice((jQuery.inArray(dato_in_mod,mail_address)),1);
        $('#email_add').val(mail_address);
    })

但是有一个问题。数组中的拼接不起作用,因为正如我在 console.log 中看到的,jQuery.inArray 返回 -1。我也尝试添加“”:

$(document).on('click','.remove_email',function(event) {
        dato_in_mod=(($(event.target).text()).replace(" ",""));
        mail_address.splice((jQuery.inArray(‘“‘+dato_in_mod+’"',mail_address)),1);
        $('#email_add').val(mail_address);
    })

谁能帮帮我?谢谢

【问题讨论】:

    标签: jquery return


    【解决方案1】:

    inArray 只会在值不在数组中时返回 -1。您说过您确定该值在数组中,但如果inArray 返回-1,它不是inArray isn't broken。所以问题是:数组中的值与dato_in_mod 中的值有什么不同?

    我的猜测是它在一个或另一个位置的末尾有一个或多个空格。您删除空格的代码

    dato_in_mod=(($(event.target).text()).replace(" ",""));
    

    仅删除字符串中的 first 空格。如果有多个,则剩余的留在字符串中。字符串上的尾随空格可能很难看到,尤其是通过console.log。使用浏览器内置的调试器停止inArray 行上的代码,然后使用调试器检查dato_in_modmail_address 变量。您可能会在其中一个或另一个上发现多余的空格,使它们不匹配。

    要从字符串中删除所有个空格,请将.replace(" ","")更改为.replace(/ /g,"")

    dato_in_mod=(($(event.target).text()).replace(/ /g,""));
    

    旁注:您不需要() 围绕单个表达式。这两行在编译/解释后是相同的:

    dato_in_mod=(($(event.target).text()).replace(/ /g,""));
    dato_in_mod=$(event.target).text().replace(/ /g,"");
    

    旁注 2:在将其传递给 splice 之前检查从 inArray 返回的索引可能是个好主意:

    var index = jQuery.inArray(dato_in_mod, mail_address);
    if (index >= 0) {
        mail_address.splice(index, 1);
    }
    

    如果不这样做,并且该值不在数组中,splice 会将负数解释为距数组末尾的偏移量,并删除错误的元素。

    【讨论】:

      【解决方案2】:

      编辑:我看到一个拼写错误。您在一处使用data_in_mod,在另一处使用dato_in_mod。这两个显然必须是相同的拼写。


      jQuery.inArray() 返回-1,当您正在搜索的数组中未找到您正在搜索的对象或您的参数不正确时。因此,要么在名为 mail_address 的数组中找不到 dato_in_mod,要么你的参数有误。

      您可以通过添加console.log() 语句以输出dato_in_modmail_address 的值来调试您自己的代码,这样您就可以查看它们是否符合您的预期,这也应该告诉您为什么dato_in_mod 是找不到。

      如果您可以备份并解释您在 click 事件中实际尝试完成的工作,我们可能会提供更好的方法。

      【讨论】:

      • 我有一个包含电子邮件地址文本字段的表单,用户可以添加多个电子邮件地址。当用户添加地址时,它会被推送到数组中;我会给用户在提交表单之前删除地址的可能性..所以这是按钮上点击事件的目标..
      • @Joe - 在填充该变量后执行console.log(data_in_mod) 并查看它到底是什么。可能不是你想的那样。这是基本的调试技术。
      • 我执行:' console.log(dato_in_mod); console.log(mail_address); pos=jQuery.inArray(dato_in_mod,mail_address); console.log(pos);' 这就是结果.. 'email@email244.it ["email@email1.it", "email@email244.it"] -1'
      • @Joe - 您正在使用不同的拼写方式,data_in_mod 在一个地方,dato_in_mod 在另一个地方。这些必须匹配。
      • 对不起,我在问题中犯了一个错误;变量到处都是 dato_in_mod,对不起 ;)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-10
      • 2015-03-04
      • 2013-10-27
      • 2016-07-28
      • 2012-04-04
      • 2010-09-30
      • 1970-01-01
      相关资源
      最近更新 更多