HTML 使用 JS 插入后实体无法正确显示

HTML entity not displaying properly after insertion using JS

我正在为我的 Pokemon 网站制作一个自动完成下拉列表,虽然自动完成下拉位有效,但它没有正确显示 HTML 个实体。当我将输入的值设置为实体时,它只是打印出文本(例如 ↑ 而不是字面上的向上箭头)。我不确定我做错了什么,但这是它的简化版本:

 // There are usually a lot more, but just for simplification only one is shown
 const natures = [
    {name: "Lonely (Atk ↑ Def↓)"}
 ]

const natureInput = document.querySelector(".natureInput");
const suggestionsPanelNature = document.querySelector(".natureSuggestions");
// This is just used to see whether they have chosen one of the options
let set_nature = 0;

natureInput.addEventListener('keyup', function() {
    set_nature = 0;
    const input = natureInput.value;
    suggestionsPanelNature.innerHTML = '';
    // Find all of the natures that start with the input
    const suggestions = natures.filter(function(nature) {
        return nature.name.toLowerCase().startsWith(input.toLowerCase());
    });
    suggestions.forEach(function(suggested) {
        // Display all matching natures
        const div = document.createElement("div");
        div.onclick = function()    {
            set_nature = 1;
            natureInput.value = suggested.name; // This is the line that seems to be causing issues
            suggestionsPanelNature.innerHTML = '';
        };
        div.classList.add("suggestion");
        div.innerHTML =  suggested.name; // This line, however, works fine
        suggestionsPanelNature.appendChild(div);
    });
    if (input === '')   {
        suggestionsPanelNature.innerHTML = '';
    }
})

所以如果有人点击Lonely(Atk↑ Def↓)选项,它会在输入框中出现Lonely(Atk↑ Def↓),这不是我想要的

如果您需要更多信息,请询问,否则提前致谢。

我假设你有一个 HTML 类似于

<input type="text" class="natureInput">
<div class="natureSuggestions"></div>

如果是这样,你只需要将&uarr;&darr;替换为↑和↓即可。 input 元素只是普通文本,所以不需要转义它(用户输入时不需要,也不需要通过 js 更改它)

Fiddle: https://jsfiddle.net/ng6er7ov/2/

(提示;post 一个完整的例子总是很好 html 和像 jsfiddle 这样的 js 这样人们就可以看到你有什么,而不是必须根据代码猜测)

目前您只是将内部 HTML 设置为您在 natures.name 中的字符串。 HTML 仅转义某些字符,例如 &<,因此您可以将 字符直接添加到字符串中。