我有一个示例JSON:
[
{
"componentid": 4,
"displayImageUrl": "https://via.placeholder.com/350x200",
"title": "theme",
"shortdesc": "to set theme for different applications"
},
{
"componentid": 7,
"displayImageUrl": "https://via.placeholder.com/350x200",
"title": "preferences",
"shortdesc": "preferences screen for apps"
}
]
我的JavaScript代码经过JSON以上并获取数据 function prepareTopComponentList(data){
try {
var preparedHtml = "";
for (var count = 0; count < data.length; count++) {
preparedHtml += "<div class=\"col-lg-4\" style=\"margin-top: 20px\">\n" +
" <div class=\"card wow fadeIn\" data-wow-delay=\"0.2s\">\n" +
" <img class=\"img-fluid\" src=\"";
preparedHtml += data[count].displayImageUrl;
preparedHtml += "\" alt=\"N/A\">\n" +
" <div class=\"card-body\">\n" +
" <h4 class=\"card-title\">";
preparedHtml += data[count].title;
preparedHtml += "</h4>\n" +
" <p class=\"card-text\">";
preparedHtml += data[count].shortdesc;
preparedHtml += "</p>\n" +
" <a onclick='Redirect(this)' href='#' class=\"btn btn-info\" id=\"";
preparedHtml += "component_desc_=" + data[count].componentid;
preparedHtml += "\">Learn more</a>\n" +
" </div>\n" +
"\n" +
" </div>\n" +
" </div>";
}
$("#div_top_component").append(preparedHtml);
} catch (err) {
}
}
function Redirect(element) {
try {
window.location = "http://localhost:9090/Reusable%20Components/pages/homepage.php?" + element.id;
} catch (err) {
}
}
我还有一个用于显示错误的HTML代码:
<!--Error/Warning Modal-->
<div class="modal fade" id="modal_show_error" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title" id="modal_error_title"></h4>
</div>
<div class="modal-body">
<p id="modal_error_description"></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal">Okay</button>
</div>
</div>
</div>
</div>
我从JSON获取componentid
。但如果是NULL
,那么我想要弹出一个引导错误,说明componentid
是NULL
。上面的JavaScript代码的Catch
块是空的,我没有得到我应该放在那里的代码来弹出引导程序错误。
答案 0 :(得分:1)
如果您希望在其中一个项目无效的情况下根本不添加任何字符串,您可以使用以下内容(我在es6中完成了,但您获得了id)
如果您只想要添加有效项目,则只需用return memo;
替换throw语句
try {
const preparedHtml = data.reduce((memo, item) => {
if(typeof(item.componentid) === typeof(null))
throw new Error(`All items must have a componentid`);
const htmlChunk = `<div class="col-lg-4" style="margin-top: 20px">\n
<div class="col-lg-4" style="margin-top: 20px">\n
<div class="card wow fadeIn" data-wow-delay="0.2s">\n
<img class="img-fluid" src="${item.displayImageUrl} alt="N/A">\n
<div class="card-body">\n
<h4 class="card-title">${item.title}</h4>\n
<p class="card-text">${item.shortdesc}</p>\n
<a onclick='Redirect(this)'
href='#' class=\"btn btn-info\" id=\""
component_desc_="${item.componentid}">Learn more</a>\n
</div>\n\n
</div>\n
</div>`;
return memo.concat(htmlChunk);
}, '');
$('#div_top_component').append(preparedHtml);
} catch (err) {
//bootstrap modal code
}
答案 1 :(得分:0)
=== 用于检查值的质量和变量的类型....
你可以这样做......
virtual