我正在运行一个switch语句,处理data-attributes
的案件很多。
目前我坚持这个:
switch(attribute) {
case "value":
case "data-vv-validations":
case "data-relation":
case "data-tolerance":
case "data-theme":
case "type":
case "readonly":
case "size":
if (setters[attribute]) {
element.setAttribute(attribute, setters[attribute]);
}
break;
}
我想知道是否可以将所有data-
属性合并到一个case
中,因为列出我遇到的所有可能选项都是“非通用”......
问题:
在CSS选择器中,我可以像[class*=" ui-icon-"]
那样做一些思考。我还可以使case
值更通用吗?
谢谢!
答案 0 :(得分:1)
简单地解决了这样的问题:
var attributeSwitch = attribute.indexOf("data-") == 0 ? "data-*" : attribute;
case(attributeSwitch){
case "value":
case "data-*":
case "type":
case "readonly":
case "size":
if (setters[attribute]) {
element.setAttribute(attribute, setters[attribute]);
}
break;
}
答案 1 :(得分:1)
排序。您可以看到第一个字符是"data-
,如果是,只需使用这些字符进行切换。
var a = attribute.slice(0, 5) === "data-" ? "data-" : attribute;
switch(a) {
case "value": case "data-": case "type": case "readonly": case "size":
if (setters[attribute]) {
element.setAttribute(attribute, setters[attribute]);
}
break;
}
这会将所有data-
属性减少为单个可测试值。请注意,您仍然使用attribute
的完整setters[]
。
或者,因为您似乎已在setters
地图中拥有属性名称,所以您可以这样做:
if (setters[attribute]) {
element.setAttribute(attribute, setters[attribute]);
}
您的switch
似乎是多余的,因为您在执行此操作时几乎执行相同的测试:
if (setters[attribute]) {
或者,如果您需要专门测试名称,那么......
if (setters.hasOwnProperty(attribute) && setters[attribute]) {
答案 2 :(得分:0)
不,你不能制作“通用案例陈述”。 但是您可以使用一组可能的值,然后检查该值是否为其中之一。
function inArray(array, value) {
for(var i=0, len=array.length; i<len; i++) {
if(array[i] == value) {
return true;
}
}
return false;
}
var possibleValues = ["value",
"data-vv-validations",
"data-relation",
"data-tolerance",
"data-theme",
"type",
"readonly",
"size"];
if (setters[attribute] && inArray(possibleValues, attribute)) {
element.setAttribute(attribute, setters[attribute]);
}