JavaScript函数中的switch语句未激活

时间:2018-05-22 01:32:47

标签: javascript jquery

我正在尝试在函数中使用switch语句,但它没有激活。

let thisFunction = function(index) {

  console.log(index);

  switch (index) {
    case 0:
      console.log('Home');
      break;

    case 1:
      console.log('About');
      break;

    case 2:
      console.log('Services');
      break;

    case 3:
      console.log('Portfolio');
      break;

    case 4:
      console.log('Contact');
      break;

    default:
      console.log('Default');
  }
};

$('nav ul li a').click(function() {
  let index = $(this).attr('data-btnIndex');
  thisFunction(index);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav>
  <ul>
    <li>
      <a href="#" data-btnIndex="0">Home</a>
    </li>
    <li>
      <a href="#" data-btnIndex="1">About Us</a>
    </li>
    <li>
      <a href="#" data-btnIndex="2">Services</a>
    </li>
    <li>
      <a href="#" data-btnIndex="3">Portfolio</a>
    </li>
    <li>
      <a href="#" data-btnIndex="4">Contact</a>
    </li>
  </ul>
</nav>

当我运行上面的代码并单击一个链接时,“index”的console.log会运行,但是switch块什么都不做。

如果我在下面的示例中定义索引变量,则交换机可以工作。但是当我在函数中放入相同的代码时,开关停止工作。

示例:

let index = 3;

console.log(index);
switch(index){
    case 0:
        console.log('Home');
    break;

    case 1:
        console.log('About');
    break;

    case 2:
        console.log('Services');
    break;

    case 3:
        console.log('Portfolio');
    break;

    case 4:
        console.log('Contact');
    break;

    default:
        console.log('Default');
}

此示例在控制台中返回“3”和“Portfolio”。

3 个答案:

答案 0 :(得分:3)

.attr会返回字符串。 (您的手动代码段将index定义为,这就是它的行为不同的原因)对case之类的数字字符串进行'0'测试,或者投射index到第一个数字:

let thisFunction = function(index) {

  console.log(index);

  switch (index) {
    case 0:
      console.log('Home');
      break;

    case 1:
      console.log('About');
      break;

    case 2:
      console.log('Services');
      break;

    case 3:
      console.log('Portfolio');
      break;

    case 4:
      console.log('Contact');
      break;

    default:
      console.log('Default');
  }
};

$('nav ul li a').click(function() {
  let index = $(this).attr('data-btnIndex');
  console.log(typeof index);
  thisFunction(Number(index));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav>
  <ul>
    <li>
      <a href="#" data-btnIndex="0">Home</a>
    </li>
    <li>
      <a href="#" data-btnIndex="1">About Us</a>
    </li>
    <li>
      <a href="#" data-btnIndex="2">Services</a>
    </li>
    <li>
      <a href="#" data-btnIndex="3">Portfolio</a>
    </li>
    <li>
      <a href="#" data-btnIndex="4">Contact</a>
    </li>
  </ul>
</nav>

答案 1 :(得分:0)

<button> vs <a>。我建议你坚持使用导航bcs的锚,这就是它的用途。重新使用您正在使用的dataset属性,它们不是必需的。只需使用innerHTML.toLowerCase()作为您的开关。

关于您的问题,您的网页会在您的脚本处理.click之前导航。

只需在页面HTML锚点中添加CSS类即可。换句话说,about.html中有<a class="active-page">About</a>

答案 2 :(得分:0)

您的代码完全正常,但只有一个小问题,会阻止正确的输出。您的交换机没有停止,它正常运行,但属性data-btnIndex的值的类型是字符串。因此,您应该写case 0而不是case '0'而不是case 1,而不是case '1',而不是data-btnIndex,等等。

或者您可以通过以下方法将var index = parseInt(index); 的值解析为Integer:

public class JSONParser {

  static InputStream is = null;
  static JSONObject jObj = null;
  static String json = "";

  // constructor
  public JSONParser() {

  }

  // function get json from url
  // by making HTTP POST or GET mehtod
  public JSONObject makeHttpRequest(String url, String method,
        List<NameValuePair> params) {

    // Making HTTP request
    try {

        // check for request method
        if(method.equals("POST")){
            // request method is POST
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        }else if(method.equals("GET")){
            // request method is GET
            DefaultHttpClient httpClient = new DefaultHttpClient();
           // String paramString = URLEncodedUtils.format(params, "utf-8");
           //url += "?" + paramString;
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }           


    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;
  }
}

我希望这会有所帮助。

感谢。