2012-07-24 5 views
3
if ($(this).hasClass('white')) {console.log('white');}; 

이 true이고 콘솔에 출력됩니다. $ (this) selector에 클래스 white이 없는지 어떻게 테스트합니까? 내가 가진 내가 가능성이 아니요() 메소드를 사용해야하고 사용하는 방법을 알아낼 수 없습니다 알고

if ($('this:not(.white)')) {console.log('not white');}; 
and 
if ($(this).not('.white')) {console.log('not white');}; 
and 
several other combinations? 

다음 $(this) 선택과 함께 선택하지.

요소를 클릭하면 true 및 false를 한 번 볼 수 있습니다.

답변

10

당신은 not logical operator을 사용할 수 있습니다,이 시도 (그렇습니다 또는 클래스 '흰색'을하지 않는 중) :

if (!$(this).hasClass('white')) {console.log('not white');}; 
의 단일 피연산자가 true로 변환 될 수 있으면

false를 반환; 그렇지 않은 경우는 true를 돌려줍니다.

2
!$(this).hasClass('white') 

자바 스크립트, 아들

2

를 사용하여 논리 NOT 연산자

if (!$(this).hasClass('white')) {console.log('not white');}; 
+1

''console.log (흰색이 아님)'';) – Luceos

1

사용 !로하지, 예를 들면 :

if (!$(this).hasClass('white')) 
    ... 
0

또는 :

<div class="vvvv vvvvv white nnnnnn" id="test"></div> 

if($("#test[class*=white]").length > 0){ 
    console.log('white'); 
}else{ 
    console.log('no white'); 
} 
5

나는 두 문장에서 교차하는 도메인을 이해하는 것이 도움이 될 것이라고 생각합니다.

if ($('this:not(.white)')) {console.log('not white');}; 

이 문이 작동하지 않습니다, 셀렉터 때문에 - this:not(.white)이 다양한 요소를 찾습니다 : <this class="white"></this>. 즉, 셀렉터는 유형이 thiswhite이 아닌 HTML 요소를 찾고 있습니다. 이 경우

if ($(this).not('.white')) {console.log('not white');}; 

, 당신은 그래서 당신이 그 DOM 요소에 대한 jQuery를 방법을 활용하는 허용하는 this 키워드가 jQuery를 객체를 참조하는 자바 스크립트 객체를 포함 $(this)을 사용하고 있습니다.

원하는 효과를 얻으려면 $(selector)에 전달하는 STRING 선택기가 CSS에서 일치 할 수있는 선택자로 제한된다는 것을 이해해야합니다. 그러므로 "this"키워드를 그렇게 사용할 수는 없습니다.

가 할 수있는 일, 당신의 효과를 확인하기 위해, 그러나, 다음과 같다 :

if ($(this).is(':not(.white)')) { 
    console.log('Not White! :('); 
} else { 
    console.log('White! :D'); 
} 

당신이 $() 블록 내부 this을 넣어 때문에, 결과는 더 jQuery를 해결하는 적용 방법을 체인이다 현재 상황에서 this이 참조하는 DOM 요소와 비교합니다. 그런 다음 CSS :not() 선택자를 사용하여 클래스를 확인합니다.

이 방법의 한계가 어떤 이유 this 여러 DOM 요소를 참조하는 경우 이러한 모든 요소가 셀렉터에 일치하는 경우 .is() 결과는 true를 반환 할 것입니다, 그러나, 유의하시기 바랍니다. - 그래서이 예제를 고려하십시오

<div class="one white element"></div> 
<div class="one black element"></div> 
<div class="one green element"></div> 

$('.one.element').bind('click', function() { 
    // In this context, 'this' refers to the element which was clicked. 
    console.log($(this).is(':not(.white)')); 

    // If you click either the black or green element, you will get a 'true', 
    // because those elements are not .white. 
    // If you click the white element, you will get a 'false', 
    // because that element does have the .white class 
}); 

문제는 내가 아는 this 매우 자주 대부분의 자바 스크립트 애플리케이션의 변화, 따라서 대부분의 프로그래머의 컨텍스트는 가능하면 그것을 사용하지 않는 것이 있습니다. 위의보다 안전 :이 경우

$('.one.element').bind('click', function (ev) { 
    var $el = $(ev.target); 
    console.log($el.is(':not(.white)')); 

    // In this case, you avoid 'this' entirely, and target the actual element 
    // from which the event originated. 
}); 

, 그러나, 당신이 잘못 목표를 제기 중첩 된 항목의 문제로 실행합니다. 당신이 parent 자체를 클릭하면 당신이 결과로 parent을 얻을 것이다,이 경우

<div class="parent"> 
    <div class="child"> 
     text 
    </div> 
</div> 

$('.parent').bind('click', function (ev) { 
    var $el = $(ev.target); 
    console.log($el.attr('class')); 
}); 

:이 경우를 생각해 보자. 그러나 자식을 클릭하면 이벤트가 부모 요소에 바인딩 되어도 이벤트 버블 링으로 인해 child이 표시됩니다. 실제 이벤트는 하위 요소에 의해 제기되었으므로 잘못 타겟팅되었습니다.

일반적으로 플러그인을 작성할 때 참조를 신중하게 관리하는 것이 좋습니다.

<div class="parent"> 
    <div class="child"> 
     text 
    </div> 
</div> 

var $parent = $('.parent').bind('click', function() { 
    console.log($parent.attr('class')); 
}); 

지금 당신이 부모 나 자녀를 클릭 여부를 중요하지 않습니다 예, 당신은 올바른 결과를 얻을, 당신은 당신이 참조하는지 알아. 하위 노드의 속성을 사용할 가능성이없고 문맥 변경이 혼동되지 않습니다.

덧붙여 말하자면 여기에있는 다른 답변에 게시 된 방법 중 하나라도 유효합니다.

// The following will all tell you if the node HAS the class: 
$(selector).hasClass('white') 
$(selector).is('.white') 
$(selector).is('[class*=white]') 

// The following will all tell you if the node DOES NOT have the class: 
!$(selector).hasClass('white') 
$(selector).not('.white') 
$(selector).is(':not(.white)') 

그리고 다른 방법이 있지만 용도에 맞게 사용할 수 있습니다. :)

+0

정확히 :) 감사합니다. 너무 많은 사람. – QMaster

관련 문제