【问题标题】:li jquery on click: if to switchli jquery on click: if to switch
【发布时间】:2018-03-21 12:09:16
【问题描述】:

我正在制作一个简单的过滤系统,其中每个 li 值都有特定的描述。 目前它正在使用 IF 语句,但我想将其转换为开关。这可能吗?

提前致谢。

我的代码:

$("ul.simplefilter").on('click', 'li', function (e) {

if($(this).text() == "Iedereen"){
    $("#uitleg p").remove();
    $("#uitleg").append("<p>Iedereen</p>");        
}
else if($(this).text() == "Coach studentenparticipatie"){ 
    $("#uitleg p").remove();    
    $("#uitleg").append("<p>Coach studentenparticipatie</p>");
}
else if($(this).text() == "Communicatie"){ 
    $("#uitleg p").remove();    
    $("#uitleg").append("<p>Communicatie</p>");
}
else if($(this).text() == "Coördinator"){ 
    $("#uitleg p").remove();    
    $("#uitleg").append("<p>Coördinator</p>");
}
})

【问题讨论】:

  • switch($(this).text) 和匹配案例case "Iedereen" : 等
  • 假设。试试看:$('#uitleg').html('&lt;p&gt;' + $(this).text() + '&lt;/p&gt;');

标签: javascript jquery html if-statement switch-statement


【解决方案1】:

这可能吗?

是的,只需使用switch 声明即可。

$("ul.simplefilter").on('click', 'li', function (e) {
   switch($(this).text()){
     case "Iedereen":
        $("#uitleg p").remove();
        $("#uitleg").append("<p>Iedereen</p>");
        break;
     case "Coach studentenparticipatie":
        $("#uitleg p").remove();    
        $("#uitleg").append("<p>Coach studentenparticipatie</p>");
        break;

   }
});

另外,您可以使用.html() 方法通过单行来实现。

$("ul.simplefilter").on('click', 'li', function (e) {
     $('#uitleg').html('<p>'+$(this).text()+'</p>');
});

例如,如果您有 100 个值,编写 100 个案例的成本很高,只需使用 .html() 方法。

【讨论】:

    【解决方案2】:

    switch 语句如下所示:

    $("ul.simplefilter").on('click', 'li', function (e) {
    
    switch($(this).text()){
        case "Iedereen" :
          $("#uitleg p").remove();
          $("#uitleg").append("<p>Iedereen</p>");
          break;
    ....
    

    PS。不要忘记每个案例上的break;。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-06
      • 1970-01-01
      • 1970-01-01
      • 2023-04-07
      • 1970-01-01
      • 1970-01-01
      • 2023-02-01
      • 1970-01-01
      相关资源
      最近更新 更多