有没有一种方法可以在每种情况下都对函数中的变量进行检查,而不必每次都将其键入?
Java脚本
function htmlParse(type) {
var returnString = "";
$('#drag-drop > .draggable').each(function() {
var item = $(this).attr('id');
switch(item) {
case 'bread-top':
returnString += '<html>';
if (type == 'string')
returnString += '\n';
break;
case 'bread-bottom':
returnString += '</html>';
if (type == 'string')
returnString += '\n';
break;
case 'turkey':
returnString += ''+
' <body>\n'+
' Your website content goes here.\n'+
' </body>';
if (type == 'string')
returnString += '\n';
break;
}
});
return returnString;
}
在此示例中,我想在开关的每种情况下都运行
if (type == 'string')...
,而不必每次都实际键入它。也许是因为来晚了,但我想不出一种方法,而不用从数组构建每个案例。
最佳答案
只需将其放在switch
之后:
var item = $(this).attr('id');
switch (item) {
case 'bread-top':
returnString += '<html>';
break;
case 'bread-bottom':
returnString += '</html>';
break;
case 'turkey':
returnString += '' +
' <body>\n' +
' Your website content goes here.\n' +
' </body>';
break;
}
if (type == 'string')
returnString += '\n';
如果需要不匹配的大小写,请添加
default
并使用标志:var item = $(this).attr('id');
var flag = true;
switch (item) {
case 'bread-top':
returnString += '<html>';
break;
case 'bread-bottom':
returnString += '</html>';
break;
case 'turkey':
returnString += '' +
' <body>\n' +
' Your website content goes here.\n' +
' </body>';
break;
default:
flag = false;
break;
}
if (flag && type == 'string')
returnString += '\n';