我有一些HTML标签,要在对象中显示为HTML(不是字符串), 问题是当我显示它时,它仍然是文本而不是HTML
var obj = { "CategoryItemID": "ID",
"ItemName": "name",
"options":"<a title='Edit' ng-click='edit()' id='btnEdit'><span class='glyphicon glyphicon-pencil' aria-hidden='true'></span></a> |" +
"<a title='Delete' ng-click='delete()' " +
"id='btnDelete'><span style='color:red' class='fa fa-times' aria-hidden='true'></span></a>",
"children": "",
}
如何以HTML格式读取对象?
答案 0 :(得分:1)
使用DOM解析器您可以在此处为示例
var obj = { "CategoryItemID": "ID",
"ItemName": "name",
"options":"<a title='Edit' ng-click='edit()' id='btnEdit'><span class='glyphicon glyphicon-pencil' aria-hidden='true'></span></a> |" +
"<a title='Delete' ng-click='delete()' " +
"id='btnDelete'><span style='color:red' class='fa fa-times' aria-hidden='true'></span></a>",
"children": "",
}
var parser = new DOMParser()
var node = parser.parseFromString(obj.options, "text/html");
console.log(node.body.innerHTML)
您要访问的内容都可以如下访问
node.body.getElementsByTagName("a")
node.body.getElementsByClassName("something")
请尝试在表中显示
var obj = { "CategoryItemID": "ID",
"ItemName": "name",
"options":"<a title='Edit' ng-click='edit()' id='btnEdit'><span class='glyphicon glyphicon-pencil' aria-hidden='true'></span></a> |" +
"<a title='Delete' ng-click='delete()' " +
"id='btnDelete'><span style='color:red' class='fa fa-times' aria-hidden='true'></span></a>",
"children": "",
}
var parser = new DOMParser()
var node = parser.parseFromString(obj.options, "text/html");
document.getElementsByClassName("option")[0].innerHTML=node.body.innerHTML;
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.8.0/css/all.min.css"/>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css"/>
<table>
<tr>
<th>Name</th>
<th>Option</th>
</tr>
<tr>
<td>Sourabh</td>
<td class="option"></td>
</tr>
</table>
答案 1 :(得分:0)
创建一个虚拟DOM元素,然后向其中添加HTML字符串。然后,您可以像处理任何DOM元素一样操作它。
var el = document.createElement( 'html' );
el.innerHTML = obj.options;
答案 2 :(得分:0)
const stringContainingHTMLSource = obj.options;
const parser = new DOMParser();
const doc = parser.parseFromString(stringContainingHTMLSource, "text/html");
答案 3 :(得分:0)
将对象属性分配给要显示的相应元素的innerHTML。
HTML
<div id="displayObject">
</div>
JS
var displayObj = document.getElementById('displayObject');
displayObj.innerHTML = obj.options;