开发者

How to use if statement in jQuery

I want to change background color each time when my_div recive class 'selected'. So far I've got this:

$(document)开发者_运维问答.ready(function() {
    if ($('#my_div').hasClass('selected')) {
        $("body").css({backgroundColor: '#111'});
    }
});

but it don't work.

What's wrong?


I want to change background color each time when my_div recive class 'selected'.

There is a piece of code which is giving your element the selected class. This piece of code effectively changes your element's class to be class = "whatever classes previously existed insertednewclass".

One way to do what you're trying to do, is to find the function which is adding/removing the class, and hook into it, for example:

myFunction = function(...) {
    $('#my_div').addClass('selected');
    // add more code
    $('#my_div').css({backgroundColor:...});
}

I assume your case is not as simple as this. However this is possible even if the function is in an external library, though it's risky if the library changes its internal behavior.

// some.function is the function which adds the "selected" class
var oldFunction = some.function;
some.function = function() {
    return oldFunction.apply(this, arguments);
}

If you cannot do that and MUST reactively detect a class attribute modification, you can use the deprecated DOM Level 2 mutation events http://www.w3.org/TR/DOM-Level-3-Events/#events-mutationevents which are vaguely supported in non-IE browsers. You can see if it is supported via $.bind in jQuery; if it isn't supported in jQuery, you can use your_element.addEventListener(...) which is the native way to do things (which is basically all that jQuery is using under the covers).


You can create a custom event that will be triggered when the selected class is set or removed.

e.g.

$(document).ready(function() {
    $('#my_div').live('myDivChangedState', function(event) {
        if($(event.target).hasClass('selected')) {
           ...
        }
    });
});

And than just trigger the event:

 $('#my_div').addClass('selected').trigger('myDivChangedState');
 -- OR --
 $('#my_div').removeClass('selected').trigger('myDivChangedState');
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜