programing

선택기가 null을 반환하는지 탐지하려면 어떻게 해야 합니까?

stoneblock 2023. 5. 29. 09:16

선택기가 null을 반환하는지 탐지하려면 어떻게 해야 합니까?

jQuery-selector가 빈 개체를 반환하는 경우 탐지하는 가장 좋은 방법은 무엇입니까?수행하는 경우:

alert($('#notAnElement'));

[ObjectObject]가 표시되므로 다음 작업을 수행할 수 있습니다.

alert($('#notAnElement').get(0));

"http://field"라고 쓰여 있을 테니 확인해 보세요.하지만 그것은 매우 나쁜 것 같습니다.다른 방법이 있나요?

제가 가장 좋아하는 것은 다음과 같은 작은 편리함으로 jQuery를 확장하는 것입니다.

$.fn.exists = function () {
    return this.length !== 0;
}

다음과 같이 사용:

$("#notAnElement").exists();

길이를 사용하는 것보다 더 명시적입니다.

if ( $("#anid").length ) {
  alert("element(s) found")
} 
else {
  alert("nothing found")
}

선택기는 jQuery 개체의 배열을 반환합니다.일치하는 요소가 없으면 빈 배열을 반환합니다.다음을 확인할 수 있습니다..length선택기에서 반환하는 컬렉션의 이름을 지정하거나 첫 번째 배열 요소가 '슬립'인지 확인합니다.

다음 예제는 IF 문 안에서 사용할 수 있으며 모두 동일한 결과를 생성합니다.True입니다. 선택기가 일치하는 요소를 발견하면 False입니다.

$('#notAnElement').length > 0
$('#notAnElement').get(0) !== undefined
$('#notAnElement')[0] !== undefined

저는 다음과 같은 일을 하는 것을 좋아합니다.

$.fn.exists = function(){
    return this.length > 0 ? this : false;
}

그러면 다음과 같은 작업을 수행할 수 있습니다.

var firstExistingElement = 
    $('#iDontExist').exists() ||      //<-returns false;
    $('#iExist').exists() ||          //<-gets assigned to the variable 
    $('#iExistAsWell').exists();      //<-never runs

firstExistingElement.doSomething();   //<-executes on #iExist

http://jsfiddle.net/vhbSG/

나는 사용하기를 좋아합니다.presenceRuby on Rails에서 영감을 받았습니다.

$.fn.presence = function () {
    return this.length !== 0 && this;
}

예는 다음과 같습니다.

alert($('#notAnElement').presence() || "No object found");

나는 그것이 제안된 것보다 우월하다고 생각합니다.$.fn.exists당신은 여전히 부울 연산자를 사용할 수 있기 때문입니다.if하지만 진실한 결과가 더 유용합니다.다른 예:

$ul = $elem.find('ul').presence() || $('<ul class="foo">').appendTo($elem)
$ul.append('...')

제가 선호하는 것은 이것이 jQuery에 없는 이유입니다.

$.fn.orElse = function(elseFunction) {
  if (!this.length) {
    elseFunction();
  }
};

다음과 같이 사용:

$('#notAnElement').each(function () {
  alert("Wrong, it is an element")
}).orElse(function() {
  alert("Yup, it's not an element")
});

또는 CoffeeScript에서 볼 수 있듯이:

$('#notAnElement').each ->
  alert "Wrong, it is an element"; return
.orElse ->
  alert "Yup, it's not an element"

다음은 JQuery 설명서에 나와 있습니다.

http://learn.jquery.com/using-jquery-core/faq/how-do-i-test-whether-an-element-exists/

  alert( $( "#notAnElement" ).length ? 'Not null' : 'Null' );

기본적으로 항상 이 작업을 수행할 수 있습니다.오류 없이 이를 수행하기 위해 jquery 함수 또는 jquery.fn.init 메서드를 랩하기 위해 애를 썼지만, 이를 위해 jquery 소스를 간단하게 변경할 수 있습니다.검색할 수 있는 주변 라인이 포함되어 있습니다.다음에 대한 jquery 소스 검색을 권장합니다.The jQuery object is actually just the init constructor 'enhanced'

var
  version = "3.3.1",

  // Define a local copy of jQuery
  jQuery = function( selector, context ) {

    // The jQuery object is actually just the init constructor 'enhanced'
    // Need init if jQuery is called (just allow error to be thrown if not included)
    var result = new jQuery.fn.init( selector, context );
    if ( result.length === 0 ) {
      if (window.console && console.warn && context !== 'failsafe') {
        if (selector != null) {
          console.warn(
            new Error('$(\''+selector+'\') selected nothing. Do $(sel, "failsafe") to silence warning. Context:'+context)
          );
        }
      }
    }
    return result;
  },

  // Support: Android <=4.0 only
  // Make sure we trim BOM and NBSP
  rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;

jQuery.fn = jQuery.prototype = {

마지막으로 http://code.jquery.com/ 에서 압축되지 않은 jquery 소스 코드를 얻을 수 있습니다.

언급URL : https://stackoverflow.com/questions/920236/how-can-i-detect-if-a-selector-returns-null