javascript - 我需要动态地使用此代码

标签 javascript switch-statement case

我有一个标题菜单,我不想为像这样的开关案例中的每个菜单链接添加,我该如何动态地做到这一点...

var sections = $(".href a");
var content = $("#load");

sections.click(function(){
    switch(this.id){            
        case ('/p/settings/header-settings'):
            $(content).load('/p/settings/header-settings #load');
            window.history.pushState('user', 'user', '/p/settings/header-settings');
            break;
        case ('/p/settings/site-verifications'):
            $(content).load('/p/settings/site-verifications #load');
            window.history.pushState('user', 'user', '/p/settings/site-verifications');
            break;
        case ('/p/settings/analysis-settings'):
            $(content).load('/p/settings/analysis-settings #load');
            window.history.pushState('user', 'user', '/p/settings/header-settings');
            break;
        default:
            $(content).load('/p #load' );
            break;
    }
}); 

最佳答案

直接传递 id 到受尊重的地方而不是 switch 。并使用 on() 动态追加元素。它的执行取决于你的 id

var sections = $(".href a");
var content = $("#load");

sections.on('click', function() {
  var id = this.id;
  if(condition) //add with some  false condition as you wish for go to  default statement s
 {
  $(content).load('/p #load' );
 }else{
  $(content).load(id + ' #load');
  window.history.pushState('user', 'user', id);
  }
});

关于javascript - 我需要动态地使用此代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44368427/

相关文章:

javascript - 将文本文件转换为 JSON

mysql - 使用CASE的SQL查询问题

linux - Shell脚本选择多次重复或退出

javascript - 具有动态字段名称的 Mongoose Model.update

javascript - async await 是否比普通 Promises 对性能要求更高?

javascript - 使用 Express 和 Node 将值传回 Jade 渲染

javascript - 在 for 循环中嵌套的 switch 语句中评估 jquery 数组的元素类名称 (javascript/jquery)

c - c中的开关和大小写如何匹配?

php - 从开关内部使用继续跳过 foreach 中的迭代

MySQL case 新建一个专栏