1. 程式人生 > >深入學習jquery原始碼之is()與not()

深入學習jquery原始碼之is()與not()

深入學習jquery原始碼之is()與not()

is(expr|obj|ele|fn)

概述

根據選擇器、DOM元素或 jQuery 物件來檢測匹配元素集合,如果其中至少有一個元素符合這個給定的表示式就返回true。

如果沒有元素符合,或者表示式無效,都返回'false'。 '''注意:'''在jQuery 1.3中才對所有表示式提供了支援。在先前版本中,如果提供了複雜的表示式,比如層級選擇器(比如 + , ~ 和 > ),始終會返回true

引數

expr String

字串值,包含供匹配當前元素集合的選擇器表示式。

jQuery object 

object

現有的jQuery物件,以匹配當前的元素。

element  Expression

一個用於匹配元素的DOM元素。

function(index) Function

一個函式用來作為測試元素的集合。它接受一個引數index,這是元素在jQuery集合的索引。在函式, this指的是當前的DOM元素。

由於input元素的父元素是一個表單元素,所以返回true。

<form><input type="checkbox" /></form>
$("input[type='checkbox']").parent().is("form")
true

判斷點選li標籤增加背景色為紅色,如果點選的是第2個strong,當前的li增加背景色為綠色

<ul>
  <li><strong>list</strong> item 1 - one strong tag</li>
  <li><strong>list</strong> item <strong>2</strong> - two <span>strong tags</span></li>
  <li>list item 3</li>
</ul>
$("li").click(function() {
  var $li = $(this),
    isWithTwo = $li.is(function() {
      return $('strong', this).length === 2;
    });
  if ( isWithTwo ) {
    $li.css("background-color", "green");
  } else {
    $li.css("background-color", "red");
  }
});

 

not(expr|ele|fn)

概述

刪除與指定表示式匹配的元素

引數

expr String

一個選擇器字串。

element DOMElement

一個DOM元素

function(index) Function

一個用來檢查集合中每個元素的函式。this是當前的元素。

從p元素中刪除帶有 select 的ID的元素

<p>Hello</p><p id="selected">Hello Again</p>
$("p").not( $("#selected")[0] )
[ <p>Hello</p> ]

 

jquery原始碼

        jQuery.fn = jQuery.prototype = {
        // The current version of jQuery being used
        jquery: version,

        constructor: jQuery,

        // Start with an empty selector
        selector: "",

        // The default length of a jQuery object is 0
        length: 0,
		
		// Take an array of elements and push it onto the stack
        // (returning the new matched element set)
        pushStack: function (elems) {

            // Build a new jQuery matched element set
            var ret = jQuery.merge(this.constructor(), elems);

            // Add the old object onto the stack (as a reference)
            ret.prevObject = this;
            ret.context = this.context;

            // Return the newly-formed element set
            return ret;
        }

        // For internal use only.
        // Behaves like an Array's method, not like a jQuery method.
        push: push,
        sort: deletedIds.sort,
        splice: deletedIds.splice
       };   

	    var rneedsContext = jQuery.expr.match.needsContext;
        var rsingleTag = (/^<(\w+)\s*\/?>(?:<\/\1>|)$/);
	    var risSimple = /^.[^:#\[\.,]*$/;

    // Implement the identical functionality for filter and not
    function winnow(elements, qualifier, not) {
        if (jQuery.isFunction(qualifier)) {
            return jQuery.grep(elements, function (elem, i) {
                /* jshint -W018 */
                return !!qualifier.call(elem, i, elem) !== not;
            });

        }

        if (qualifier.nodeType) {
            return jQuery.grep(elements, function (elem) {
                return (elem === qualifier) !== not;
            });

        }

        if (typeof qualifier === "string") {
            if (risSimple.test(qualifier)) {
                return jQuery.filter(qualifier, elements, not);
            }

            qualifier = jQuery.filter(qualifier, elements);
        }

        return jQuery.grep(elements, function (elem) {
            return (jQuery.inArray(elem, qualifier) >= 0) !== not;
        });
    }

   jQuery.fn.extend({
        not: function (selector) {
            return this.pushStack(winnow(this, selector || [], true));
        },
        is: function (selector) {
            return !!winnow(
                this,

                // If this is a positional/relative selector, check membership in the returned set
                // so $("p:first").is("p:last") won't return true for a doc with two "p".
                typeof selector === "string" && rneedsContext.test(selector) ?
                jQuery(selector) :
                selector || [],
                false
            ).length;
        }
    });