我有以下JS代码(带有一些jQuery),它将数组中的错误输出到bootstrap容器:
var errors = [{
"Message": "The source document is not valid. Please see the 'Schema
Validation Issues' section above at column &1, line &2"
}, {
"Message": "The metadata element \"Resource Title\" is missing, empty or
incomplete but it is required. Hint: \"A non-empty title is required for
Spatial Data Sets and Spatial Data Set Series but none could be found.\"",
}, {
"Message": "In content of element <CI_Citation>: The content model does not
allow element <Q{.../gmd}date> to appear as the first child. It must be preceded by <Q{.../gmd}title>. at column 31, line 73",
}];
$.each(errors, function(key, val) {
var output = document.createElement("div");
output.setAttribute("class", "alert alert-danger");
output.innerHTML = '<strong>Error: </strong>'+val.Message;
output.getElementById('container').appendChild(output);
});
由于我的一些消息包含HTML / XML标记(请参阅消息3),因此它们将打印为HTML而不是纯字符串。我该怎么逃避这个?我需要将这些消息打印为字符串。
答案 0 :(得分:2)
您应该使用innerText属性,如下面显示的代码段示例所示。
var errors = [{
"Message": "The source document is not valid. Please see the 'Schema Validation Issues' section above at column &1, line &2"
}, {
"Message": "The metadata element \"Resource Title\" is missing, empty or incomplete but it is required. Hint: \"A non-empty title is required for Spatial Data Sets and Spatial Data Set Series but none could be found.\"",
}, {
"Message": "In content of element <CI_Citation>: The content model does not allow element <Q{.../gmd}date> to appear as the first child. It must be preceded by <Q{.../gmd}title>",
}];
$.each(errors, function(key, val) {
var output = document.createElement("div");
var outputText = document.createElement("div");
output.setAttribute("class", "alert alert-danger");
output.innerHTML = '<strong>Error: </strong>'+ val.Message;
outputText.innerText = val.Message;
document.getElementById('container').appendChild(output);
document.getElementById('containerText').appendChild(outputText);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container"></div>
<br/><br/><br/>
<div id="containerText"></div>