我正在添加一些条件逻辑来检查数组中的元素,如果它们存在,则使用 JS 生成的标记添加类来执行此操作。有没有办法在两个字符串(作为标记从 JS 输出)之间添加条件逻辑来减少一些冗余的条件逻辑?
for (var i=0; i<data.length; i++) {
var gallery = data[i];
if (typeof gallery.showcase !== "undefined") {
if (typeof gallery.video !== "undefined") {
$(
"<li class='video " + (typeof gallery.video !== "undefined" ? "test ") + gallery.showcase + "'>" +
"<a href='" + gallery.link + "'></a>" +
"</li>").appendTo("#gallery ul");
}
else {
$(
"<li class='image " + gallery.showcase + "'>" +
"<a href='" + gallery.link + "'>" +
"<img src=" + gallery.image + " alt='" + gallery.title + "'>" +
"</a>"
+ "</li>").appendTo("#gallery ul");
}
}
else {
if (typeof gallery.video !== "undefined") {
$(
"<li class='video'>" +
"<a href='" + gallery.link + "'></a>" +
"</li>").appendTo("#gallery ul");
}
else {
$(
"<li class='image'>" +
"<a href='" + gallery.link + "'>" +
"<img src=" + gallery.image + " alt='" + gallery.title + "'>" +
"</a>"
+ "</li>").appendTo("#gallery ul");
}
}
}
我希望以更简洁的方式将类添加到 JS 生成的标记中进行条件检查。想法?