所以这是我的问题......我在JS文件中有这样的图标:
function iconValues() {
// Icon svg-s
var icons = {
home:
'<svg xmlns="http://www.w3.org/2000/svg" version="1.1" x="0" y="0" viewBox="-293 385 24 24" xml:space="preserve"><path d="M-283 405v-6h4v6h5v-8h3l-10-9 -10 9h3v8H-283z"/></svg>',
user:
'<svg xmlns="http://www.w3.org/2000/svg" version="1.1" x="0" y="0" width="409.2" height="409.2" viewBox="0 0 409.2 409.2" xml:space="preserve"><path d="M204.6 216.7c50.7 0 91.7-48.1 91.7-107.4 0-82.2-41.1-107.4-91.7-107.4 -50.7 0-91.7 25.1-91.7 107.4C112.8 168.6 153.9 216.7 204.6 216.7zM407.2 374.7L360.9 270.5c-2.1-4.8-5.8-8.7-10.5-11.1l-71.8-37.4c-1.6-0.8-3.5-0.7-4.9 0.4 -20.3 15.4-44.2 23.5-69.1 23.5 -24.9 0-48.8-8.1-69.1-23.5 -1.4-1.1-3.3-1.2-4.9-0.4L58.8 259.3c-4.6 2.4-8.3 6.4-10.5 11.1L2 374.7c-3.2 7.2-2.5 15.4 1.8 22 4.3 6.6 11.5 10.5 19.4 10.5h362.9c7.9 0 15.1-3.9 19.4-10.5C409.7 390.1 410.4 381.9 407.2 374.7z"/></svg>'
我在html中包含了JS脚本。现在我想知道如何在(li)html中包含其中一个图标?例如:
<li><a href="dashboard.html">Home</a> </li>
我需要写什么(li)来向我展示我需要的图标?
谢谢。
答案 0 :(得分:1)
例如......
var icons = {
home:
'<svg xmlns="http://www.w3.org/2000/svg" version="1.1" x="0" y="0" viewBox="-293 385 24 24" xml:space="preserve"><path d="M-283 405v-6h4v6h5v-8h3l-10-9 -10 9h3v8H-283z"/></svg>',
user:
'<svg xmlns="http://www.w3.org/2000/svg" version="1.1" x="0" y="0" width="409.2" height="409.2" viewBox="0 0 409.2 409.2" xml:space="preserve"><path d="M204.6 216.7c50.7 0 91.7-48.1 91.7-107.4 0-82.2-41.1-107.4-91.7-107.4 -50.7 0-91.7 25.1-91.7 107.4C112.8 168.6 153.9 216.7 204.6 216.7zM407.2 374.7L360.9 270.5c-2.1-4.8-5.8-8.7-10.5-11.1l-71.8-37.4c-1.6-0.8-3.5-0.7-4.9 0.4 -20.3 15.4-44.2 23.5-69.1 23.5 -24.9 0-48.8-8.1-69.1-23.5 -1.4-1.1-3.3-1.2-4.9-0.4L58.8 259.3c-4.6 2.4-8.3 6.4-10.5 11.1L2 374.7c-3.2 7.2-2.5 15.4 1.8 22 4.3 6.6 11.5 10.5 19.4 10.5h362.9c7.9 0 15.1-3.9 19.4-10.5C409.7 390.1 410.4 381.9 407.2 374.7z"/></svg>',
};
// insert
var target = document.querySelectorAll('a[data-icon-key]');
for (var i = 0; i < target.length; i++) {
var key = target[i].getAttribute('data-icon-key');
if (icons[key]) {
// if you want to append the icon
var temp = document.createElement('div');
temp.innerHTML = icons[key];
target[i].appendChild(temp.firstChild);
// if you want to replace the content of <a>
//target[i].innerHTML = icons[key];
}
}
a > svg { height: 16px; }
<ul>
<li><a href="dashboard.html" data-icon-key="home">Home</a></li>
<li><a href="usermenu.html" data-icon-key="user">User</a></li>
</ul>
具有<a>
属性的每个data-icon-key
元素,例如foo
,它将添加图标icons['foo']
。