简体   繁体   English

使用Jquery:比较两个数组以进行任何匹配

[英]Using Jquery: Comparing Two Arrays for ANY Match

I'm looking for a concise way to compare two arrays for any match. 我正在寻找一种简洁的方法来比较任何匹配的两个数组。

I am using this comparison to apply a particular style to any table cell that has matching content. 我正在使用此比较将特定样式应用于具有匹配内容的任何表格单元格。 One array is a static list of content that should be contained in at least one table cell on the page. 一个数组是一个静态的内容列表,应该包含在页面上的至少一个表格单元格中。 The other array is being generated by JQuery, and is the text of all table cells. 另一个数组由JQuery生成,是所有表格单元格的文本。

The reason why I have to compare content to apply style is that the HTML document will semantically change over time, is being generated by different versions of excel (pretty awful looking code), and this script needs to accommodate that. 我必须比较内容和应用样式的原因是HTML文档将随着时间的推移在语义上发生变化,由不同版本的excel生成(非常糟糕的代码),并且此脚本需要适应这种情况。 I know that the content I'm looking to apply the style to in this document will never change, so I need to detect all matches for this content to apply styles to them. 我知道我希望在本文档中应用样式的内容永远不会改变,因此我需要检测此内容的所有匹配项以将样式应用于它们。

So, the code should be something like (in english): 所以,代码应该是(英文):

for each table cell, compare cell text to contents of array. 对于每个表格单元格,将单元格文本与数组内容进行比较。 If there is any match, apply this css to the table cell. 如果有任何匹配,请将此css应用于表格单元格。

This is what I have so far (and I know it's wrong): 这是我到目前为止(我知道这是错的):

$(document).ready(function(){
    $("a.loader").click(function(event){
         event.preventDefault();
         var fileToLoad = $(this).attr("href");
         var fileType = $(this).text();
         var makes = new Array("ACURA","ALFA ROMEO","AMC","ASTON MARTIN","ASUNA","AUDI","BENTLEY","BMW","BRITISH LEYLAND","BUICK","CADILLAC","CHEVROLET","CHRYSLER","CITROEN","COLT","DACIA","DAEWOO","DELOREAN","DODGE","EAGLE","FERRARI","FIAT","FORD","GEO","GMC","HONDA","HUMMER","HYUNDAI","INFINITI","INNOCENTI","ISUZU","JAGUAR","JEEP","KIA","LADA","LAMBORGHINI","LANCIA","LAND ROVER","LEXUS","LINCOLN","LOTUS","M.G.B.","MASERATI","MAYBACH","MAZDA","MERCEDES BENZ","MERCURY","MG","MINI","MITSUBISHI","MORGAN","NISSAN (Datsun)","OLDSMOBILE","PASSPORT","PEUGEOT","PLYMOUTH","PONTIAC","PORSCHE","RANGE ROVER","RENAULT","ROLLS-ROYCE / BENTLEY","SAAB","SATURN","SCION","SHELBY","SKODA","SMART","SUBARU","SUZUKI","TOYOTA","TRIUMPH","VOLKSWAGEN","VOLVO","YUGO","Acura","Alfa Romeo","Amc","Aston Martin","Asuna","Audi","Bentley","Bmw","British Leyland","Buick","Cadillac","Chevrolet","Chrysler","Citroen","Colt","Dacia","Daewoo","Delorean","Dodge","Eagle","Ferrari","Fiat","Ford","Geo","Gmc","Honda","Hummer","Hyundai","Infiniti","Innocenti","Isuzu","Jaguar","Jeep","Kia","Lada","Lamborghini","Lancia","Land Rover","Lexus","Lincoln","Lotus","M.G.B.","Maserati","Maybach","Mazda","Mercedes Benz","Mercury","Mg","Mini","Mitsubishi","Morgan","Nissan (Datsun)","Oldsmobile","Passport","Peugeot","Plymouth","Pontiac","Porsche","Range Rover","Renault","Rolls-Royce / Bentley","Saab","Saturn","Scion","Shelby","Skoda","Smart","Subaru","Suzuki","Toyota","Triumph","Volkswagen","Volvo","Yugo");
         $("div#carApp").html("<img src='images/loadingAnimation.gif' alt='LOADING...' />");
         $("div#carApp").load(fileToLoad, function(){
             $("#carApp style").children().remove();
             $('#carApp td').removeAttr('style');
             $('#carApp td').removeAttr('class');
             $('#carApp table').removeAttr('class');
             $('#carApp table').removeAttr('style');
             $('#carApp table').removeAttr('width');
             $('#carApp tr').removeAttr('style');
             $('#carApp tr').removeAttr('class');
             $('#carApp col').remove();
             $('#carApp table').width('90%');
             var content = $("#carApp table td");
             jQuery.each(content, function() {
                 var textValue = $(this).text();
                 if (jQuery.inArray(textValue, makes)==true)
                    $(this).css("color","red");
             });
         });
    });
});

Any ideas? 有任何想法吗?

You're checking $.inArray(...) == true . 你正在检查$.inArray(...) == true inArray actually returns an integer with the index of the item in the array (otherwise -1 .) So you want to check if it is greater than or equal to 0 . inArray实际上返回一个整数,其中包含数组中项的索引(否则为-1 。)因此,您要检查它是否大于或等于0

Here's how you can change your each loop. 以下是如何更改each循环的方法。

$('#carApp td').each(function () {
    var cell = $(this);
    if ($.inArray(cell.text(), makes) >= 0) {
        cell.addClass('selected-make');
    }
});

I use a CSS class instead of the style attribute, because it's better practice to put styling in a CSS file rather than in your JavaScript code. 我使用CSS类而不是style属性,因为将样式放在CSS文件而不是JavaScript代码中更好。 Easier to update that way (especially when you want to apply the same style in multiple places in your code.) 更容易以这种方式更新(特别是当您想在代码中的多个位置应用相同的样式时。)

Other points worth noting: 其他值得注意的地方:

  • jQuery selections have the each(...) function as well. jQuery选择也有each(...)函数。 So you can do $(...).each(...) instead of jQuery.each($(...), ...) 所以你可以做$(...).each(...)而不是jQuery.each($(...), ...)
  • jQuery and $ are the same object as long as you don't have other frameworks that redefine the $ variable. 只要你没有重新定义$变量的其他框架, jQuery$就是同一个对象。 Therefore you can do $.inArray(...) instead of jQuery.inArray(...) . 因此,您可以执行$.inArray(...)而不是jQuery.inArray(...) It's a matter of taste, though. 不过,这是一个品味问题。

Have you had a look at $.grep() ? 你看过$.grep()吗?

Finds the elements of an array which satisfy a filter function. 查找满足过滤函数的数组元素。 The original array is not affected. 原始数组不受影响。 The filter function will be passed two arguments: the current array item and its index. filter函数将传递两个参数:当前数组项及其索引。 The filter function must return 'true' to include the item in the result array. filter函数必须返回'true'才能在结果数组中包含该项。

An optimization would be to make makes a hash (aka dictionary): 优化将是制作哈希(又名字典):

var makes = { "ACURA": 1,"ALFA ROMEO": 1,"AMC": 1, ...};

Then you don't have to iterate makes every time with inArray. 然后你不必每次使用inArray迭代make。

...
var textValue = $(this).text();
  if (makes[textValue] == 1)
    $(this).css("color","red");
  }
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM