【发布时间】:2021-03-15 10:29:07
【问题描述】:
我遇到了这个问题。因此,每次我在输入标签中输入新单词时,我的网站都会创建一个新对象,然后该对象显示在列表中,我希望在对象文本的同一行中的某处有一个垃圾桶图标。这是我留下的地方,代码显示的不是图标,而是整个图标代码。有任何想法吗? 我的代码:
const alert = document.querySelector('#alert');
let words = [];
const addWord = (ev) => {
ev.preventDefault();
if (
document.getElementById('input-first-text').value !== '' &&
document.getElementById('input-second-text').value !== ''
) {
let word = {
id: Date.now(),
homeLanguageWord: document.getElementById('input-first-text').value,
foreignLanguageWord: document.getElementById('input-second-text').value,
};
words.push(word);
document.getElementById('input-first-text').value = '';
document.getElementById('input-second-text').value = '';
console.warn('added', { words });
if (words.length != 0) {
let para = document.createElement('li');
let node = document.createTextNode(
words[words.length - 1].homeLanguageWord + ' ' + words[words.length - 1].foreignLanguageWord,
);
para.appendChild(node);
let nodeIcon = document.createTextNode(`<svg width="1em" height="1em" viewBox="0 0 16 16" class="bi bi-trash" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
<path d="M5.5 5.5A.5.5 0 0 1 6 6v6a.5.5 0 0 1-1 0V6a.5.5 0 0 1 .5-.5zm2.5 0a.5.5 0 0 1 .5.5v6a.5.5 0 0 1-1 0V6a.5.5 0 0 1 .5-.5zm3 .5a.5.5 0 0 0-1 0v6a.5.5 0 0 0 1 0V6z"/>
<path fill-rule="evenodd" d="M14.5 3a1 1 0 0 1-1 1H13v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V4h-.5a1 1 0 0 1-1-1V2a1 1 0 0 1 1-1H6a1 1 0 0 1 1-1h2a1 1 0 0 1 1 1h3.5a1 1 0 0 1 1 1v1zM4.118 4L4 4.059V13a1 1 0 0 0 1 1h6a1 1 0 0 0 1-1V4.059L11.882 4H4.118zM2.5 3V2h11v1h-11z"/>
</svg>`);
para.appendChild(nodeIcon);
var element = document.getElementById('word-list');
element.appendChild(para);
}
document.getElementById('alert').innerHTML = '';
} else {
document.getElementById('alert').innerHTML = 'You need to write something!';
}
};
document.getElementById('submitbtn').addEventListener('click', addWord);
【问题讨论】:
-
看看这个惊人的答案:stackoverflow.com/a/14070928/10915534
-
我尝试更改为 createElementNS(),但它仍然不适合我
标签: javascript html