Programing

현재 노드를 포함하는 jQuery find (..) 메소드를 찾고 있습니다.

crosscheck 2020. 7. 17. 19:18
반응형

현재 노드를 포함하는 jQuery find (..) 메소드를 찾고 있습니다.


jQuery find (..) 순회 메소드는 현재 노드를 포함하지 않습니다. 현재 노드의 하위로 시작합니다. 일치하는 알고리즘에 현재 노드를 포함하는 찾기 작업을 호출하는 가장 좋은 방법은 무엇입니까? 문서를 살펴보면 아무것도 즉시 나에게 튀어 나오지 않습니다.


jQuery 1.8 이상에서는을 사용할 수 있습니다 .addBack(). 선택기가 필요하므로 결과를 필터링하지 않아도됩니다.

object.find('selector').addBack('selector')

jQuery 1.8 이전에는 .andSelf()필터링이 필요한, (이제 더 이상 사용되지 않고 제거되었습니다.)

object.find('selector').andSelf().filter('selector')

내가 직접 생각할 수없는, 내가 생각할 수있는 가장 가까운 것은 다음과 같이 사용 .andSelf()하고 호출하는 것입니다 .filter().

$(selector).find(oSelector).andSelf().filter(oSelector)
//or...
$(selector).find('*').andSelf().filter(oSelector);

불행히도 .andSelf()선택기를 사용하지 않으므로 편리합니다.


밝히다

$.fn.findSelf = function(selector) {
    var result = this.find(selector);
    return (this.is(selector)) ?
        result.add(this) : result;
};

그런 다음 사용

$.findSelf(selector);

대신에

$find(selector);

슬프게도 jQuery에는이 내장 기능이 없습니다. 수년간의 개발로 정말 이상합니다. .find () 작동 방식으로 인해 AJAX 핸들러가 일부 최상위 요소에 적용되지 않았습니다.


$('selector').find('otherSelector').add($('selector').filter('otherSelector'))

$('selector')속도 향상을 위해 변수에 저장할 수 있습니다 . 필요한 경우 사용자 정의 함수를 작성할 수도 있습니다.

$.fn.andFind = function(expr) {
  return this.find(expr).add(this.filter(expr));
};

$('selector').andFind('otherSelector')

허용되는 답변은 매우 비효율적이며 이미 일치하는 요소 집합을 필터링합니다.

//find descendants that match the selector
var $selection = $context.find(selector);
//filter the parent/context based on the selector and add it
$selection = $selection.add($context.filter(selector);

나는 이것이 오래된 질문이라는 것을 알고 있지만 더 정확한 방법이 있습니다. 예를 들어와 같은 선택기를 일치시킬 때 순서가 중요한 :first경우 find()실제로 현재 요소 집합을 포함하는 것과 동일한 결과를 반환하는 작은 함수를 작성했습니다 .

$.fn.findAll = function(selector) {
  var $result = $();

  for(var i = 0; i < this.length; i++) {
    $result = $result.add(this.eq(i).filter(selector));
    $result = $result.add(this.eq(i).find(selector));
  }

  return $result.filter(selector);
};

어떤 방법으로도 효율적이지는 않지만 적절한 순서를 유지하기 위해 내가 찾은 최고입니다.


체인이 제대로 작동하려면 아래 스 니펫을 사용하십시오.

$.fn.findBack = function(expr) {
    var r = this.find(expr);
    if (this.is(expr)) r = r.add(this);
    return this.pushStack(r);
};

end 함수를 호출 한 후 #foo 요소를 반환합니다.

$('#foo')
    .findBack('.red')
        .css('color', 'red')
    .end()
    .removeAttr('id');

추가 플러그인을 정의하지 않으면이 문제가 발생합니다.

$('#foo')
    .find('.red')
        .addBack('.red')
            .css('color', 'red')
        .end()
    .end()
    .removeAttr('id');

andSelf당신이 원하는 것 같아요 :

obj.find(selector).andSelf()

선택기와 일치하는지 여부에 관계없이 항상 현재 노드를 다시 추가합니다.


현재 노드를 엄격히 찾고 있다면 간단히 수행하십시오.

$(html).filter('selector')

현재 요소 또는 내부의 요소 중 하나정확히 찾고있는 경우 다음 을 사용할 수 있습니다.

result = elem.is(selector) ? elem : elem.find(selector);

여러 요소찾는 경우 다음 을 사용할 수 있습니다.

result = elem.filter(selector).add(elem.find(selector));

andSelf/ 사용 andBack은 매우 드물지만 왜 그런지 확실하지 않습니다. 아마도 성능 문제로 인해 일부 사람들이 앞에서 언급했습니다.

(I now noticed that Tgr already gave that second solution)


Here's the right (but sad) truth:

$(selector).parent().find(oSelector).filter($(selector).find('*'))

http://jsfiddle.net/SergeJcqmn/MeQb8/2/

참고URL : https://stackoverflow.com/questions/2828019/looking-for-jquery-find-method-that-includes-the-current-node

반응형