Jquery inArray 总是在循环中返回 -1

Jquery inArray always returns -1 in loop

本文关键字:返回 循环 inArray Jquery      更新时间:2023-09-26

我在使用Jquery inArray时遇到了问题。

//Get selected devices
selectedDevices = $('.selectDevices').val();
console.log(selectedDevices);
//If nothing selected, do nothing
if(selectedDevices == null || selectedDevices == ""){}
    //Else remove devices not selected
    else{ 
        //Loop thru table rows with class "enhet"
        $.each( $('td.enhet'), function() {
        thisDevice = $('.enhet').text();
        var found = $.inArray(thisDevice, selectedDevices);
        console.log(found);
        if (found > -1) {
            console.log(thisDevice);
        }
        else {
            console.log('nope');
        }

    })
}

控制台.log(选定设备(给出:

["GulAvformning", "RosaAvformning"]

控制台.log(找到(给:(每次!!

-1

控制台.log(此设备(给出:
''

控制台.log("不"(给出:

nope

即使thisdevice存在于selectedDevices我也会得到其他情况。
我错过了什么?

selectedDevices是一个数组。我通过以下方式检查了它:控制台.log(选定的设备[1](;它给了我一个设备。

对元素使用 each() 方法,然后使用 $(this) 标识当前元素:

selectedDevices = $('.selectDevices').val();
console.log(selectedDevices);
//If nothing selected, do nothing
if(selectedDevices == null || selectedDevices == ""){}
//Else remove devices not selected
else{ 
  //Loop thru table rows with class "enhet"
  $('td.enhet').each(  function() {
    thisDevice = $(this).text(); // use $(this) here
    var found = $.inArray(thisDevice, selectedDevices);
    console.log(found);
    if (found > -1) {
      console.log(thisDevice);
    }
    else {
      console.log('nope');
    }

  })
}

使用:

thisDevice = $(this).text();

而不是:

thisDevice = $('.enhet').text();

您正在迭代,但未选择迭代器。将您的行更改为以下内容:...

$.each( $('td.enhet'), function(i) {
        thisDevice = $('td.enhet').eq(i).text();

如果console.log(selectedDevices)给出["GulAvformning", "RosaAvformning"],而console.log(thisDevice)给出"",那么$.inArray(thisDevice, selectedDevices)将返回-1,因为["GulAvformning", "RosaAvformning"]中没有""。请参阅马科斯·佩雷斯·古德的解决方案,了解有关如何正确获取正确值thisDevice的更多信息。