나는 두 문장에서 교차하는 도메인을 이해하는 것이 도움이 될 것이라고 생각합니다.
if ($('this:not(.white)')) {console.log('not white');};
이 문이 작동하지 않습니다, 셀렉터 때문에 - this:not(.white)
이 다양한 요소를 찾습니다 : <this class="white"></this>
. 즉, 셀렉터는 유형이 this
인 white
이 아닌 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)')
그리고 다른 방법이 있지만 용도에 맞게 사용할 수 있습니다. :)
''console.log (흰색이 아님)'';) – Luceos