>  기사  >  웹 프론트엔드  >  jQuery 객체에서 선택기와 컨텍스트를 사용하는 방법은 무엇입니까?

jQuery 객체에서 선택기와 컨텍스트를 사용하는 방법은 무엇입니까?

伊谢尔伦
伊谢尔伦원래의
2017-06-16 13:29:371642검색

jQuery 객체의 두 가지 속성인 selector와 context가 처음에는 전혀 명확하지 않았습니다. 그러다가 Baidu와 Google에서 오랫동안 검색했지만 나중에 jQuery에서 이 jquery 객체를 발견했습니다. API 문서 선택기 속성 및 컨텍스트 속성. 하하~ 그럼~ 시간이 나면 jQuery API 문서를 먼저 훑어보고 익숙해지는 것이 나처럼 아직도 인터넷에서 찾고 있지만 찾지 못하는 것보다 낫습니다. 네~ 이 글을 읽는 학생들이 아직도 이 두 속성의 의미를 모른다면 여기서 배워보세요. 사실 이 두 속성의 가장 큰 용도는 플러그인을 작성하는 것입니다. .

API 문서에 따르면:
기본적으로 context 매개변수가 지정되지 않은 경우 $()는 DOM 요소 세트 또는 jQuery 객체와 같은 context 매개변수가 지정된 경우 현재 HTML 문서에서 DOM 요소를 검색합니다. then 이 컨텍스트에서 검색됩니다. jQuery 1.3.2 이후에는 반환된 요소의 순서가 컨텍스트에 나타나는 순서와 동일합니다.

Context 매개변수는 작업 노드 객체(jQuery 객체가 아닌 DOM 객체)여야 합니다. jQuery 객체를 전달하면 검색 범위가 제한될 수도 있지만 이 경우 jQuery 객체의 context 속성은 전체 Document 객체가 됩니다.

$(expression, [context]).selector의 값은 정확히 표현식입니다
예:

 $("div ul").selector//值为“div ul”    
 $("div.test").selector//值为“div.test”    
 $("#test ul li:first").selector//值为“test ul li:first”

즉, 표현식이 무엇이든 선택기는

$(expression, [context])입니다. 컨텍스트는 DOM 객체입니다. 이 DOM 개체와 관련하여 다른 $(expression, [context])를 사용하면 얻는 컨텍스트 개체가 다릅니다.

관련 샘플 코드:

function( selector, context, rootjQuery ) {var match, elem, ret, doc;// Handle $(""), $(null), or $(undefined)
        //如果selector为空格,!selector为false
if (!selector) {//此时this为空jQuery对象
return this;
}// Handle $(DOMElement)
        //nodeType节点类型,利用是否有nodeType属性来判断是否是DOM元素
if ( selector.nodeType ) {//将第一个元素和属性context指向selector
this.context = this[0] = selector;this.length = 1;return this;
}// The body element only exists once, optimize finding it
        //因为body只出现一次,利用!context进行优化
if ( selector === "body" && !context && document.body ) {//context指向document对象
this.context = document;this[0] = document.body;this.selector = selector;this.length = 1;return this;
}// Handle HTML strings
if ( typeof selector === "string" ) {    // Are we dealing with HTML string or an ID?
//以<开头以>结尾,且长度大于等于3,这里假设是HTML片段,跳过queckExpr正则检查
if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {// Assume that strings that start and end with <> are HTML and skip the regex check
match = [ null, selector, null ];
} else {
match = quickExpr.exec( selector );
}// Verify a match, and that no context was specified for #id
if ( match && (match[1] || !context) ) {// HANDLE: $(html) -> $(array)
if ( match[1] ) {
context = context instanceof jQuery ? context[0] : context;
doc = ( context ? context.ownerDocument || context : document );// If a single string is passed in and it&#39;s a single tag
// just do a createElement and skip the rest
ret = rsingleTag.exec( selector );        //如果是单独标签
if (ret) {//如果context是普通对象
    if (jQuery.isPlainObject(context)) {    //之所以放在数组中,是方便后面的jQuery.merge()方法调用
    selector = [document.createElement(ret[1])];    //调用attr方法,传入参数context
jQuery.fn.attr.call( selector, context, true );
} else {
selector = [ doc.createElement( ret[1] ) ];
}        //复杂HTML的处理方法
} else {
ret = jQuery.buildFragment( [ match[1] ], [ doc ] );
selector = ( ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment ).childNodes;
}return jQuery.merge( this, selector );// HANDLE: $("#id")
} else {
elem = document.getElementById( match[2] );// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {// Handle the case where IE and Opera return items
    // by name instead of ID
    //即使是documen.getElementById这样核心的方法也要考虑到浏览器兼容问题,可能找到的是name而不是id
if ( elem.id !== match[2] ) {return rootjQuery.find( selector );
}// Otherwise, we inject the element directly into the jQuery object
this.length = 1;this[0] = elem;
}this.context = document;this.selector = selector;return this;
}// HANDLE: $(expr, $(...))
//没有指定上下文,执行rootjQuery.find(),制定了上下文且上下文是jQuery对象,执行context.find()
} else if ( !context || context.jquery ) {return ( context || rootjQuery ).find( selector );// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
//如果指定了上下文,且上下文不是jQuery对象
} else {    //先创建一个包含context的jQuery对象,然后调用find方法
return this.constructor( context ).find( selector );
}// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {return rootjQuery.ready( selector );
}        //selector是jquery对象
if ( selector.selector !== undefined ) {this.selector = selector.selector;this.context = selector.context;
}        //合并到当前jQuery对象
return jQuery.makeArray( selector, this );
}

위 내용은 jQuery 객체에서 선택기와 컨텍스트를 사용하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.