【问题标题】:jquery get multidimensional array based on parentjquery根据父级获取多维数组
【发布时间】:2015-12-12 01:32:30
【问题描述】:

我正在尝试创建一个 ajax 过滤器,在我的后端我需要为每个过滤器设置单独的数组。所以我可以运行多个其中。 我的 HTML 看起来像:

<div class="products-filter-page">
    <input data-id="18" type="checkbox" value="" class="checkbox-filter-option">test
    <input data-id="19" type="checkbox" value="" class="checkbox-filter-option">test
    <input data-id="20" type="checkbox" value="" class="checkbox-filter-option">test
</div>

<div class="products-filter-page">
    <input data-id="21" type="checkbox" value="" class="checkbox-filter-option">test
    <input data-id="22" type="checkbox" value="" class="checkbox-filter-option">test
    <input data-id="22" type="checkbox" value="" class="checkbox-filter-option">test
</div>

现在,当我选择某些内容时,我会在 ajax 调用中发送所有选定的数据 ID。但是我希望他们根据他们的父母分开。例如,我有数据 id 为 18,19 和 22 的过滤器

18,19 有相同的父级,所以我有 1 个数组 [18,19] 和一个数组 [22]。

我当前的代码得到了所有需要的东西,除了基于父级的分离。

 var filterProducts = function() {
   var selectedItems = [];
   $(".checkbox-filter-option:checked").each(function () {
     selectedItems.push($(this).data('id'));
   });
   console.log(selectedItems);
   if(selectedItems.length > 0){

     /*$.ajax({
           data : { ids:selectedItems
           //some calls
        });
     */
   }

 };

$( ".checkbox-filter-option" ).on( "click", filterProducts );

Fiddle

【问题讨论】:

    标签: jquery arrays ajax


    【解决方案1】:

    我在这里为你做了一个例子:http://jsfiddle.net/4wot3o8a/2/

    var selectedItems = [[],[]];
    $(".checkbox-filter-option:checked").each(function() {
      if ($(this).parent()[0] == $(".products-filter-page")[0] ) {
        selectedItems[0].push($(this).data('id'));
      } else {
        selectedItems[1].push($(this).data('id'));
      }
    });
    

    希望这可以帮助您实现您的目标。

    【讨论】:

      【解决方案2】:

      将您的 html 部分更改为 &lt;input data-id="18" type="checkbox" value="" class="checkbox-filter-option" name=filter-X&gt; 对于第 1 组过滤器 1 和第 n 组过滤器 2。

      Var filterVal = {}; Each loop{ Var Name =$(this).attr('nane')]; If(!filterVal[Name])filterVal[Name]=[]; filterVal[Name].push($(this).data('id')); }

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-11-23
        • 2012-01-18
        • 1970-01-01
        • 1970-01-01
        • 2017-01-04
        • 2016-09-27
        • 2021-06-23
        相关资源
        最近更新 更多