开发者

Jquery - putting variables in :contains()

开发者 https://www.devze.com 2022-12-24 18:37 出处:网络
I am trying to write a simple piece of Jquery in which the script will check whether a table cell contains a range of numbers.

I am trying to write a simple piece of Jquery in which the script will check whether a table cell contains a range of numbers.

I'm unsure how to do this, because if you were to do something like this:

var num_range = ">1";
$("td:contains(" + num_range + ")").css('background-color', '#000');
开发者_StackOverflow

...the script only detects if the td contains the exact text ">1", rather than what I'm after, it detecting whether any tds contain any numbers greater than 1. (Any then styling the background)

Thanks for any help, I'm a Javascript/Jquery novice!


There's no native jQuery selector for this. You could write one if you want or just use:

$("td").each(function() {
  if (parseInt($(this).text()) > 1) {
    $(this).css("background", "#000");
  }
});

If you want to create your own selector:

$.extend($.expr[":"], {
  expr: (function() {
    var op = {
      '=': function(n1, n2) { return n1 == n2; },
      '!=': function(n1, n2) { return n1 != n2; },
      '>': function(n1, n2) { return n1 > n2; },
      '>=': function(n1, n2) { return n1 >= n2; },
      '<': function(n1, n2) { return n1 < n2; },
      '<=': function(n1, n2) { return n1 <= n2; }
    };
    var ops = [];
    for (p in op) {
      ops.push(p);
    }
    var r = new RegExp("^\\s*(" + ops.join("|") + ")\\s*(-?\\d+(?:\\.\\d+)?)\\s*$");
    return function(elem, i, match) {
      var m = r.exec(match[3]);
      return m && op[m[1]](parseFloat($(elem).text()), parseFloat(m[2]));
    };
  })()
});

And then you can do:

$("td:expr(>5)").css("background", "yellow");


There is no built-in selector in jQuery that does this.

You can use .filter to manually fund the elements. (by calling .text in the filter)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号