【问题标题】:jQuery replacement for switchjQuery替换开关
【发布时间】:2010-08-14 13:58:40
【问题描述】:

美好的一天。

我正在寻找 jQuery 中的 switch 替代品。基本上,我不知道如何替换switch

我在大约 70 个国家/地区关注了 switch。有什么办法可以用loop代替吗?

$("#country").change(function () {
  switch ($('#country :selected').val()) {
  case 'pl':
    $("fieldset#state").hide().load('pl.txt').fadeIn(800);
    break;
  }
});

另外,如果已经有选择的项目,是否有可能实现自动加载特定文件?

编辑:

我对问题的描述不是最好的。对此感到抱歉。主要问题是:

  • 我只有部分国家/地区的列表,而不是所有国家/地区的列表
  • 我是用switch来读取国家/地区的文件,如果没有,我默认插入文本字段
  • 我还需要默认实现加载文件。我是什么意思?我查询国家/地区的数据库,然后在国家/地区下拉列表中选择它。如何自动加载文件(如果有)?

问候, 汤姆

【问题讨论】:

    标签: jquery switch-statement


    【解决方案1】:

    你可以这样做:

    $("#country").change(function () {
      $("fieldset#state").hide().load($('#country :selected').val() + '.txt').fadeIn(800);
    });
    

    编辑
    对于可用的国家列表,您可以将它们放在一个数组中,然后进行搜索

    $("#country").change(function () {
        var supportCountries = ['pl',]; //put more here
        var country = $('#country :selected').val();
        if(supportCountries.indexOf(country))
            $("fieldset#state").hide().load(country + '.txt').fadeIn(800);
        else
            $("fieldset#state").hide().load('default.txt').fadeIn(800); //here is load the default text, change if you has another way.
    });
    

    更详细的,如果你想替换switch,那么让我们使用for/loop找到匹配的case,然后执行那个case的动作。

    【讨论】:

    • 无需再次运行选择器,因为this 指的是<select>。只需执行$(this).val()this.value(如果选项具有值属性)。
    • @patrick dw:实际上,我们不知道$('#country :selected')$("#country") 是否是一个对象,所以我一直使用$('#country :selected') 以便Tom 更容易理解。
    • 太棒了!谢谢,我必须继续学习和练习!谢谢!
    • 什么意思?页面上只能有一个#country 元素。并且做$(this).val() 你选择的选项的价值。
    【解决方案2】:

    这个怎么样,它假设您遵循在文本文件“pl.txt”的名称中使用国家代码“pl”的约定......

    $("#country").change(function () {
        var fileName = $('#country :selected').val() + '.txt';
        $("fieldset#state").hide().load(fileName).fadeIn(800);
    });
    

    【讨论】:

      【解决方案3】:

      如果文本文件总是与表单元素中的值同名,那么你可以像这样创建一个变量

        $("#country").change(function () {
          var counrty = $('#country :selected').val();
      
              $("fieldset#state").hide().load(country+ '.txt').fadeIn(800);
      
          }
      });
      

      【讨论】:

        【解决方案4】:

        您能否创建一个关联数组(即对象),以所有 $('#country :selected').val() 值为键并映射到 1) 函数或 2) 具有适合您要为每个操作执行的操作的字段的对象?

        那你就可以了

        var lookup = { 'p1': function() { $("fieldset#state").hide().load('pl.txt').fadeIn(800); } }
        //or
        var lookup = { 'p1': { selector: 'p1.txt', speed: 800 } };
        
        action = lookup[$('#country :selected').val()];
        
        action();
        //or 
        $("fieldset#state").hide().load(action.selector).fadeIn(action.speed)
        

        【讨论】:

          猜你喜欢
          • 2018-09-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-12-04
          • 1970-01-01
          • 2021-02-24
          相关资源
          最近更新 更多