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

后端 未结 9 1844
鱼传尺愫
鱼传尺愫 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:19

      I improved upon psycho brm's filterByData extension to jQuery.

      Where the former extension searched on a key-value pair, with this extension you can additionally search for the presence of a data attribute, irrespective of its value.

      (function ($) {
      
          $.fn.filterByData = function (prop, val) {
              var $self = this;
              if (typeof val === 'undefined') {
                  return $self.filter(
                      function () { return typeof $(this).data(prop) !== 'undefined'; }
                  );
              }
              return $self.filter(
                  function () { return $(this).data(prop) == val; }
              );
          };
      
      })(window.jQuery);
      

      Usage:

      $('').data('x', 1).filterByData('x', 1).length    // output: 1
      $('').data('x', 1).filterByData('x').length       // output: 1
      

      // test data
      function extractData() {
        log('data-prop=val ...... ' + $('div').filterByData('prop', 'val').length);
        log('data-prop .......... ' + $('div').filterByData('prop').length);
        log('data-random ........ ' + $('div').filterByData('random').length);
        log('data-test .......... ' + $('div').filterByData('test').length);
        log('data-test=anyval ... ' + $('div').filterByData('test', 'anyval').length);
      }
      
      $(document).ready(function() {
        $('#b5').data('test', 'anyval');
      });
      
      // the actual extension
      (function($) {
      
        $.fn.filterByData = function(prop, val) {
          var $self = this;
          if (typeof val === 'undefined') {
            return $self.filter(
      
              function() {
                return typeof $(this).data(prop) !== 'undefined';
              });
          }
          return $self.filter(
      
            function() {
              return $(this).data(prop) == val;
            });
        };
      
      })(window.jQuery);
      
      
      //just to quickly log
      function log(txt) {
        if (window.console && console.log) {
          console.log(txt);
          //} else {
          //  alert('You need a console to check the results');
        }
        $("#result").append(txt + "
      "); }
      #bPratik {
        font-family: monospace;
      }
      
      
      

      Setup

      Data added inline :: data-prop="val"
      Data added inline :: data-prop="val"
      Data added inline :: data-prop="diffval"
      Data added inline :: data-test="val"
      Data will be added via jQuery

      Output


      Or the fiddle: http://jsfiddle.net/PTqmE/46/

    提交回复
    热议问题