jQuery how to find an element based on a data-attribute value?

后端 未结 9 1805
鱼传尺愫
鱼传尺愫 2020-11-22 01:02

I\'ve got the following scenario:

var el = \'li\';

and there are 5

  • \'s on the page each with a data-slide=numb
  • 9条回答
    •  温柔的废话
      2020-11-22 01:22

      When searching with [data-x=...], watch out, it doesn't work with jQuery.data(..) setter:

      $(''  ).is('[data-x=1]') // this works
      > true
      
      $('').data('x', 1).is('[data-x=1]') // this doesn't
      > false
      
      $('').attr('data-x', 1).is('[data-x=1]') // this is the workaround
      > true
      

      You can use this instead:

      $.fn.filterByData = function(prop, val) {
          return this.filter(
              function() { return $(this).data(prop)==val; }
          );
      }
      
      $('').data('x', 1).filterByData('x', 1).length
      > 1
      

    提交回复
    热议问题