Jquery switch case plugin?

I know that the case switch statement is an integral part of javascript, and you cannot change it. I'm still learning javascript and jQuery, so I can get around it, but I don’t know enough to write something that might be at the level of jQuery itself. So, take this as an idea or a question about whether this idea is possible.

This is my idea, a case switch statement that can use objects ... which can be used something like this:

switch( $(this) ){

 case .hasClass('foo'):
  // do something
  break;

 case .filter('.bar').attr('id') == 'foo':
  // do something else
  break;

}

Edit: even something like this would be nice (maybe a more sensible idea) ...

switch ($(this).hasClass()) {

 case 'foo':
  alert('found a foo!');
  break;

 case 'bar':
  alert('found a bar!');
  break;

}
+3
source share
5 answers

- , jQuery , switch:

(function($) {
    $.fn.switchClasses = function(switches) {
        return this.each(function() {
            var that = this;
            $.each(this.attr("class").split(' '), function(i, class) {
                var func = switches[class];
                if(func)
                    func.apply(that, class);
            });
        });
    };
})(jQuery);

:

$(this).switchClasses(
    {
        "class1":
        function(class) {
            // Do something for this class, 
            // the "this" variable is the jquery object that matched the class
        },

        "class2":
        function(class) {

        }
    }
);
+3

-, switch int. , javascript C/++, .

if-then-else , .

, C ++, , "break", goto, . ( if-else-else), goto . C/++ goto , if ( ) .

switch (1) { //yes, that is a hardcoded 1, we only want the switch block for the break keyword
    if (yourString == "Case 1") {
        do_stuff_1();
        break; // well, we're done, let get out of here.
    }

//implicit else - if you matched the first one, you'd be out of here

    if (yourString == "Case 2") {
        do_stuff_2();
        break; // well, we're done, let get out of here.
    }

    // etc.....

    default:
        do_error_condition();
} //end of switch
+1

if/else?

inst = $(this);

if (inst.hasClass('foo')) {
    // do something
} else if (inst.filter('.bar').attr('id') == 'foo') {
    // do something else
}
0

element.attr('class'), .

, element.attr('class').split(/\s+/) .

, .is(). , if( element.is('a.foo') ) console.log( 'This is a link with a 'foo' class.' );

, . , , .

0
    (function($) {
    $.fn.switchClasses = function(switches) {
        return this.each(function() {
            var that = this;
            $.each(this.attr("class").split(' '), function(i, classname) {
                var func = switches[classname];
                if(func){
                    func.apply(that, classname);
                }
            });
        });
    };
})(jQuery);

'class' is a reserved name and I added some missing parentheses

0
source

Source: https://habr.com/ru/post/1720949/


All Articles