我知道switch case语句是javascript固有的,你无法改变它。我还在学习javascript和jQuery,所以我可以顺利完成,但是我不知道写一些可能在jQuery本身的内容。所以,把这个作为一个想法或一个关于这个想法是否可行的问题。

这是我的想法,一个可以使用对象的switch case语句......可以使用这样的东西:

switch( $(this) ){

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

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

}

编辑:即使这样的事情也会很好(可能是一个更合理的想法)......

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

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

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

}
有帮助吗?

解决方案

通常,switch不是解决问题的最佳方法,但是使用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) {

        }
    }
);

其他提示

首先,switch语句仅适用于int。我不确定为什么javascript会从C / C ++中保留这个限制,但它就在那里。

如果您正在处理多个选项,那么使用嵌套的if-then-else块而不是切换可能会导致代码难以读取。

然而,就像在C和C ++中一样,有一些解决方法,这个涉及使用“break”和“break”。像goto一样,并不总是邪恶的。这是一种情况(大量的嵌套if-the-else),其中goto会使代码更有效和可读。在C / 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's 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's get out of here.
    }

    // etc.....

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

正常的 if / else 有什么问题?

inst = $(this);

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

如果您正在处理一个类名,可以打开 element.attr('class')

如果您正在处理多个,可以执行 element.attr('class')。split(/ \ s + /)并检查该数组中的类名。

我也认为你可能想看一下 .is()。您可以执行以下操作: if(element.is('a.foo'))console.log('这是带'foo'类的链接。');

您可能想要改变您的方法。我不认为这是你做你想做的最有效的方式。

    (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'是保留名称, 我添加了一些缺失的括号

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top