Transferring values using js switch

时间:2016-02-03 04:29:18

标签: javascript jquery switch-statement

Using jStorage.js, I've transferred some values, referring to English programs like "starting", "primary", "uni" and so on, from one page to another in a Joomla site using this script. This works OK. Each of the values is displayed in the title on its relevant second page. Here is the js:

jQuery(document).ready(function(){
 "use strict";
  jQuery("p.enrol_para").on("click", function(evnt){
      var elementId = evnt.target.id;
       jQuery.jStorage.set("program", elementId);
     });
  jQuery("div#register_title").prepend(document.createTextNode(jQuery.jStorage.get("program")+" "));
});

and the html fragment:

<p class="enrol_para"><span class="enrol_text"><a href="/index.php/registration-starting" id="starting" class="enrol_btn">Enrol/ลงทะเบียน</a></span></p>

However, what I want is for "starting" to show "Starting English", "primary" to show "Primary School" and so on. I tried to do this using a js switch statment in this way:

jQuery(document).ready(function(){
    "use strict";
    jQuery("p.enrol_para").on("click", function(evnt){
        var elementId = evnt.target.id;
         jQuery.jStorage.set("program", elementId);
    });
    var progName = JQuery.jStorage.get("program");
        switch (progName){
        case "starting":
          jQuery("div#register_title").prepend(document.createTextNode("Starting English"+" "));
          break;
        case "primary":
          jQuery("div#register_title").prepend(document.createTextNode("Primary School English"+" "));
          break;
        case "high":
          jQuery("div#register_title").prepend(document.createTextNode("High School English"+" "));
          break;
        case "senior":
          jQuery("div#register_title").prepend(document.createTextNode("Senior School English"+" "));
          break;
        case "uni":
          jQuery("div#register_title").prepend(document.createTextNode("University English"+" "));
          break;
        case "profession":
          jQuery("div#register_title").prepend(document.createTextNode("Professional and Career English"+" "));
          break;
        default:
          jQuery("div#register_title").prepend(document.createTextNode("General English"+" "));
        }
});

But this doesn't work. Nothing is displayed in the various page titles. JSHint has OKed the syntax. I thought that using a switch statement would be the best way to go here, but perhaps not. Any help would be much appreciated.

1 个答案:

答案 0 :(得分:0)

这是完成这个技巧的脚本:

jQuery(document).ready(function(){
   "use strict";
    jQuery("a.enrol_btn").on("click", function(){
         jQuery.jStorage.set("program", jQuery(this).attr("data-program"));
    });
    jQuery("div#register_title").prepend(document.createTextNode(jQuery.jStorage.get("program")));
});