如何遍历数组并查找与数组中的值匹配

时间:2017-07-12 04:21:05

标签: javascript jquery arrays string-matching

我有两组数据,其值由data-attribute(data-product-name)抓取,1是可用项目的整个列表,另一个是选定项目,对于选定项目,它们附加到一个国家/地区。

    <!-- the item list -->
    <div class="whole_list">
      <ul>
        <li data-product-name="a">item A<button>ATTACH</button></li>
        <li data-product-name="b">item B<button>ATTACH</button></li>
        <li data-product-name="c">item C<button>ATTACH</button></li>
        <li data-product-name="d">item D<button>ATTACH</button></li>
        <li data-product-name="e">item E<button>ATTACH</button></li>
      </ul>
    </div>

    <!-- selected item block -->
    <div class="selected_item_container"> 
      <ul class="selected_items">
        <li data-product-name="a">item A</li>
        <li data-product-name="b">item B</li>
        <li data-product-name="e">item E</li>
      </ul>
      <button class="edit_country">EDIT</button>
    </div>


    $('.edit_country').on('click', function () {
      // to grab text/string from .whole_list data-product-name
      var productName = []; // product name
      $('.whole_list li').each(function (index) {
        productName .push($(this).data('product-name'));
      });

      // to grab text/string from .selected_item_container data-product-name
      var selProductName = []; // selected product name
        $('.selected_item_container').find('[data-product-name]').each(function () {
         selProductName .push($(this).data('product-name'));
       });

      // if the string/text matches, change the button text
      $('.whole_list li').each(function (index) {
      if ($(this).data('product-name') === arrProductName[index]) {                         
        $(this).find('button').text('DETACH');
        } else {
          $(this).find('button').text('ATTACH');
        }
      });
    });

理想情况下,当用户点击edit_country按钮时,.whole_list已将所选项目按钮更改为DETACH文本。我试过了,但问题是,它只改变了项目A&amp;项目B按钮,项目E按钮无变化。

我认为这与索引不匹配有关。我不确定,请指教,谢谢。

Demo site

2 个答案:

答案 0 :(得分:0)

使用.indexOf查找数组中是否存在值 像这样:

arrProductName.indexOf( $(this).data('product-name') ) != -1

因为,使用$(this).data('product-name') === arrProductName[index] ...
如果您的数组如下:

var arrProductName = ["a","c","d"];

a将在索引0处找到,
找不到b
c索引处找到2 wil NOT ...它是d
d索引处找到3 wil NOT ...它是undefined
找不到e

CodePen中查看。

答案 1 :(得分:0)

尝试以下代码

$('.edit_country').on('click', function() {
  // to grab text/string from .whole_list data-product-name
  var productName = []; // product name
  $('.whole_list li').each(function(index) {
    productName.push($(this).data('product-name'));
  });

  // to grab text/string from .selected_item_container data-product-name
  var selProductName = []; // selected product name
  $('.selected_item_container').find('[data-product-name]').each(function() {
    selProductName.push($(this).data('product-name'));
  });

  $(selProductName).each(function(index) {
    $('.whole_list li[data-product-name=' + selProductName[index] + ']').find('button').text('DETACH');
  });

});