如何在 jQuery/Javascript 中编写 switch 语句来测试元素是否具有特定的类?

发布于 2024-12-05 07:31:33 字数 466 浏览 0 评论 0原文

这是我正在使用的 if-else 语句的结构:

$('.myclass a').click(function() {
   if ($(this).hasClass('class1')) {
        //do something
   } else if ($(this).hasClass('class2')) {
        //do something
   } else if ($(this).hasClass('class3')) {
        //do something
   } else if ($(this).hasClass('class4')) {
        //do something
   } else {
        //do something
   }
});

已经有相当多的情况了,我认为使用 switch 语句会更简洁。我如何在 jQuery/javascript 中做到这一点?

This is the structure of the if-else statement I am using:

$('.myclass a').click(function() {
   if ($(this).hasClass('class1')) {
        //do something
   } else if ($(this).hasClass('class2')) {
        //do something
   } else if ($(this).hasClass('class3')) {
        //do something
   } else if ($(this).hasClass('class4')) {
        //do something
   } else {
        //do something
   }
});

There are quite a number of cases already and I thought using a switch statement would be neater. How do I do it in jQuery/javascript?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

紅太極 2024-12-12 07:31:33

试试这个。不太干净,但仍然是一个 switch 语句。

$('.myclass a').click(function() {
    switch (true) {
      case $(this).hasClass('class1'):
        // do stuff
        break;
      case $(this).hasClass('class2'):
        // do stuff
        break;
      case $(this).hasClass('class3'):
        // do stuff
        break;
    }
}

Try this. Not much cleaner, but still a switch statement.

$('.myclass a').click(function() {
    switch (true) {
      case $(this).hasClass('class1'):
        // do stuff
        break;
      case $(this).hasClass('class2'):
        // do stuff
        break;
      case $(this).hasClass('class3'):
        // do stuff
        break;
    }
}
没︽人懂的悲伤 2024-12-12 07:31:33

问题是一个用户可能拥有多个类。否则你可以这样做:

$('.myclass a').click(function() {
   var className = $(this).attr('class');
   switch(className){
      case 'class1':
     //put your cases here
   }
});

The problem is that an user could have more than one class. Otherwise you could do:

$('.myclass a').click(function() {
   var className = $(this).attr('class');
   switch(className){
      case 'class1':
     //put your cases here
   }
});
赏烟花じ飞满天 2024-12-12 07:31:33

我认为最干净的方法可能就是这样:

$('.myclass a.class1').click(function() {
   // code to process class1
});

$('.myclass a.class2').click(function() {
   // code to process class2
});

$('.myclass a.class3').click(function() {
   // code to process class3
});

$('.myclass a.class4').click(function() {
   // code to process class4
});

如果您有无数个对象,您甚至可以将它们放入这样的数据结构中:

// to define them all
var classHandlers = {
    class1: function() {
        // class1 code here
    },
    class2: function() {
        // class2 code here
    },
    class3: function() {
        // class3 code here
    },
    class4: function() {
        // class4 code here
    }
};

// to register them all
$.each(classHandlers, function(key, fn) {
    $('.myclass a.' + key).click(fn);
});

既然您(在评论中)询问了如何为对象执行事件处理程序没有类名,如果您正在寻找没有类名,那么您可以这样做:

$(".myclass a").not("[class]").click(function() {
    // code to handle objects with no class name here
});

我在这里测试了它:http://jsfiddle.net/jfriend00/TAjKR/

I think the cleanest way might just be this:

$('.myclass a.class1').click(function() {
   // code to process class1
});

$('.myclass a.class2').click(function() {
   // code to process class2
});

$('.myclass a.class3').click(function() {
   // code to process class3
});

$('.myclass a.class4').click(function() {
   // code to process class4
});

If you had a zillion of them, you could even put them in a data structure like this:

// to define them all
var classHandlers = {
    class1: function() {
        // class1 code here
    },
    class2: function() {
        // class2 code here
    },
    class3: function() {
        // class3 code here
    },
    class4: function() {
        // class4 code here
    }
};

// to register them all
$.each(classHandlers, function(key, fn) {
    $('.myclass a.' + key).click(fn);
});

Since you've asked (in a comment) how you would do an event handler for the objects with no class name, here's how you could do that if you were looking for no class name:

$(".myclass a").not("[class]").click(function() {
    // code to handle objects with no class name here
});

I tested it out here: http://jsfiddle.net/jfriend00/TAjKR/

怪我鬧 2024-12-12 07:31:33

我认为单个 switch 语句在这里没有帮助,因为一个元素可以有多个类,并且您不能使用 elem.className 进行切换。一种选择是以更具可读性的方式构建代码,使用 for 语句,其中包含开关...:

$('.myclass a').click(function() 
{
    var classes = ["class1", "class2", "class3","class4"];
    var self = $(this);
    for(var i =0, ii = classes.length;i<ii;i++)
    {
        var className = classes[i];
        if(self.hasClass(className))
        {
            switch(className)
            {
                case 'class1':
                    //code here... 
                break;
                case 'class2':
                    //code here... 
                break;      
                case 'class3':
                    //code here... 
                break;     
                case 'class4':
                    //code here... 
                break;
            }

        }
    }       
});

I do not think that a single switch statement will help here, because one element can have multiple classes, and you cannot use elem.className to switch. An option is to structure the code in a more readable way, using a for statement in which to have switches...:

$('.myclass a').click(function() 
{
    var classes = ["class1", "class2", "class3","class4"];
    var self = $(this);
    for(var i =0, ii = classes.length;i<ii;i++)
    {
        var className = classes[i];
        if(self.hasClass(className))
        {
            switch(className)
            {
                case 'class1':
                    //code here... 
                break;
                case 'class2':
                    //code here... 
                break;      
                case 'class3':
                    //code here... 
                break;     
                case 'class4':
                    //code here... 
                break;
            }

        }
    }       
});
若有似无的小暗淡 2024-12-12 07:31:33

要检查 switch 语句中的 hasClass:

var elementClass;
var classCheck = $('#myElement').hasClass(elementClass)

switch(classCheck){
  case elementClass === 'foo':
     console.log('whatever');
     break;
}

To check hasClass in an switch statement:

var elementClass;
var classCheck = $('#myElement').hasClass(elementClass)

switch(classCheck){
  case elementClass === 'foo':
     console.log('whatever');
     break;
}
深海夜未眠 2024-12-12 07:31:33

我知道这已经晚了,您的用户只有一门课程,但是,如果有多个课程:

//<div class="foo bar"></div>
//<div class="other bar"></div>

switch(true) {
  case 'foo':
    true;
    break;
  case 'other':
    true;
}

I know this is late and your user only has one class, but, if there was more than one class:

//<div class="foo bar"></div>
//<div class="other bar"></div>

switch(true) {
  case 'foo':
    true;
    break;
  case 'other':
    true;
}
假情假意假温柔 2024-12-12 07:31:33
    $("#isTest").click(function () {

	  if($('div').is('.redColor')){
	  	$('div').addClass('blueColor');
	  }

    });

    $("#hasClassTest").click(function () {

	  if($('div').hasClass('.redColor')){
	  	$('div').addClass('blueColor');
	  }

    });

	$("#reset").click(function () {
	  location.reload();
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<style type="text/css">
  .redColor {
  	background:red;
  }
  .blueColor {
  	background:blue;
  }
 </style>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
</head>
<body>
  <h1>jQuery check if an element has a certain class</h1>

  <div class="redColor">This is a div tag with class name of "redColor"</div>

  <p>
  <button id="isTest">is('.redColor')</button>
  <button id="hasClassTest">hasClass('.redColor')</button>
  <button id="reset">reset</button>
  </p>

</body>
</html>

    $("#isTest").click(function () {

	  if($('div').is('.redColor')){
	  	$('div').addClass('blueColor');
	  }

    });

    $("#hasClassTest").click(function () {

	  if($('div').hasClass('.redColor')){
	  	$('div').addClass('blueColor');
	  }

    });

	$("#reset").click(function () {
	  location.reload();
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<style type="text/css">
  .redColor {
  	background:red;
  }
  .blueColor {
  	background:blue;
  }
 </style>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
</head>
<body>
  <h1>jQuery check if an element has a certain class</h1>

  <div class="redColor">This is a div tag with class name of "redColor"</div>

  <p>
  <button id="isTest">is('.redColor')</button>
  <button id="hasClassTest">hasClass('.redColor')</button>
  <button id="reset">reset</button>
  </p>

</body>
</html>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文