Thứ Hai, 7 tháng 12, 2015

Create custom filters

<pre>
<ul class="levels">
  <li data-level="1" data-points="1" data-technologies="javascript node
grunt">Level 1</li>
  <li data-level="2" data-points="10" data-technologies="php composer">Level
2</li>
  <li data-level="3" data-points="100" data-technologies="jquery
requirejs">Level 3</li>
  <li data-level="4" data-points="1000" data-technologies="javascript jquery
backbone">Level 4</li>
</ul>
</pre>
Now imagine you often need to retrieve levels (data-level) higher than 2 but only if
they allow you to earn more than 100 points (data-points) and have jQuery in the
list of the technologies to employ (data-technologies). Using the knowledge you’ve
acquired so far, you know how to search li elements having the word jquery inside the
attribute data-technologies (li[data-technologies~="jquery"]). But how do you
perform a number comparison using selectors? The truth is you can’t. To accomplish
this task, you must loop over your initial selection and then retain only the elements
you need, as shown here:

$.expr[':'].requiredLevel = $.expr.createPseudo(function(filterParam) {
  return function(element, context, isXml) {
    return element.getAttribute('data-level') > 2 &&
           element.getAttribute('data-points') > 100;
  };
});
var $elements = $('.levels requiredLevel ()').css('color','#f00');

Không có nhận xét nào:

Đăng nhận xét