[jquery] 선택기가 null을 반환하는지 어떻게 알 수 있습니까?

jQuery 선택기가 빈 객체를 반환하는지 감지하는 가장 좋은 방법은 무엇입니까? 당신이 할 경우 :

alert($('#notAnElement'));

[object Object]를 얻게되므로 지금하는 방법은 다음과 같습니다.

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

“정의되지 않음”으로 표시되므로이를 확인할 수 있습니다. 그러나 그것은 매우 나쁜 것 같습니다. 다른 방법은 무엇입니까?



답변

내가 가장 좋아하는 것은이 작은 편의로 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/


답변

Ruby on Railspresence 에서 영감을 얻은 을 사용 하고 싶습니다 .

$.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' );