开发者

How to compare $(this)?

How to make this 开发者_如何学JAVAcorrect?

if( $(this) == $(".className") ){
   alert("Yes!");
}

and the NOT...

if( $(this) != $(".className") ){
   alert("Yes!");
}

Thank you


if($(this).hasClass("className")){
    alert('is class');
}else{
    alert('is not class');
}


What your code would do is to compare a jQuery object containing one element with another jQuery object containing all elements with a specific class, so that would supposedly (i.e. if it would have worked) be true if the element has that class, and it's the only element with that class. I don't think that's what you want to do...

If you want to check if the element has a class:

if ($(this).hasClass('className')) {
   alert("Yes!");
}

if (!$(this).hasClass('className')) {
   alert("No!");
}


Assuming your $(this) is an element, you can check if it has the class ‘className’:

if ($(this).is('.className')) {
     //$(this) has the class
} else {
     //$(this) doesn't have the class
}


It is not clear what you want to do but if you want to compare two jQuery objects to determine if they are the same (ie. values, keys, the whole lot) you should use an object comparison function.

Some examples could be found here Object comparison in JavaScript

or you could use underscore.js to perform the comparison

http://documentcloud.github.com/underscore/#isEqual


You can compare the HTML elements:

$(this).get(0) == $(".className").get(0);
$(this).get(0) != $(".className").get(0); 

Taken from jQuery mailing list:

// Plugin:
(function($){
    jQuery.fn.equals = function(selector) {
        return $(this).get(0)==$(selector).get(0);
    };
})(jQuery); 

// Can be used as:
if (  $(this).equals( $(".className") )) {
   alert('SAME');
} else {
   alert('Not the same');
}


For the little jQuery I remember the following:

$(".className")

is a selector so returns you a list of objects,

how does it work if your replace it with:

$(".className")[0]

??

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜