【问题标题】:Select the elements with at least one value in their data attribute, which is included in a certain array选择数据属性中至少有一个值的元素,该值包含在某个数组中
【发布时间】:2017-08-15 16:36:29
【问题描述】:

我正在编写一个过滤函数,其中我需要选择在其数据属性中具有特定值的元素,并且这些值包含在一个数组中,请允许我举例说明:

例如,我有三个元素和一个按钮如下:

<div data-foo="aa,cc,ff" ></div>
<div data-foo="bb,cc,ff" ></div>
<div data-foo="bb,dd,ee" ></div>

<div class="button" data-boo="aa,ff" ></div>

每个元素中的 data-foo 包含逗号分隔的值。当我点击按钮时,我从它的数据属性中创建了一个数组(myArray 在下面的代码中),然后我需要选择那些至少具有该@987654323 中的一个值的元素@在他们的data-foo中,为了清楚的解释请看下面的代码:

$( ".button" ).click(function() {

     // First I make an array from the button's data attribute 
     var myArray = $(this).data('boo').split(',');


     // Select should be elements that their da-foo has at least one 
     // — of values in the array above
     var Select = "?"

});

Select 变量如何定位前两个元素,因为第一个元素同时具有“aa”和“ff”,而第二个元素具有“ff”。

我真的尽力把它说得通了,如果不够清楚,请告诉我,我很乐意解释更多,谢谢。

【问题讨论】:

    标签: javascript jquery arrays sorting


    【解决方案1】:

    你可以使用Attribute Contains Selector:

    $( ".button" ).click(function() {
        // First I make an array from the button's data attribute 
        var myArray = $(this).data('boo').split(',');
    
        // produces array of strings like '[data-foo*="aa"]'
        var selectors = myArray.map(function(value) {
            return '[data-foo*="' + value + '"]';
        });
        // searches by selectors joined by comma, returns all elements
        // that satisfy at least one selector
        var selectedElements = $(selectors.join(','));
    });
    

    【讨论】:

      【解决方案2】:

      让我们使用Array.prototype.some

      $(".button").click(function() {
      
        // First I make an array from the button's data attribute 
        var myArray = $(this).data('boo').split(',');
      
      
        // Select should be elements that their da-foo has at least one 
        // — of values in the array above
        var Select = $("div[data-foo]"); //select all elements with data-foo
        Select.each(function(index, element) {
          var isInMyArray = $(element).data("foo").split(",").some(function(element) {
      
           if ( myArray.indexOf(element) != -1)
            {return true;}//if true then element is in myArray
      
          }); //using some here - if one value is found in array return true.
          console.log(isInMyArray);
        });
      
      });
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      <div data-foo="aa,cc,ff"></div>
      <div data-foo="bb,cc,ff"></div>
      <div data-foo="bb,dd,ee"></div>
      
      <div class="button" data-boo="aa,ff">test</div>

      【讨论】:

        猜你喜欢
        • 2023-04-03
        • 2021-02-06
        • 2020-04-05
        • 2017-05-13
        • 1970-01-01
        • 1970-01-01
        • 2018-06-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多