javascript - Switch case as string -
$(document).ready(function(){ createform("text,password",".content"); }); function createform(types,object){ typ = types.split(','); //var source = ""; $.each(typ,function(){ switch(this){ case "text": console.log('text');break; default: console.log('default');break; } }); //$(object).html(source); }
i have code in console homecoming 2xdefaults. why?
i seek homecoming input each type text or password switch not recognize "typ"
the reason you're seeing behavior this
within each
phone call string
object instance, not string primitive. javascript has both. in switch
statement, comparing cases via ===
, , string instance not ===
string primitive.
three ways prepare it:
if alter switch to:
switch (string(this)) {
...that turn primitive, whereupon switch
works.
as vision points out in comments below, utilize arguments $.each
passes (each string — primitive — provided sec argument):
$.each(typ, function(index, value) { switch (value) { // ... } });
use of the alternatives discussed in other answer (one of nice simple for
loop).
side note: you're falling prey the horror of implicit globals not declaring typ
variable.
javascript
No comments:
Post a Comment