最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to set emoji unicode dynamically - Stack Overflow

programmeradmin1浏览0评论

This is what my html code looks like:

<html>
<style>
    body {
        font-size: 18px;
    }
</style>
<body>
    <span id="tiger" style='font-size:100px;'>&#128161;</span>
    <button id="btn">SET TIGER</button>

    <script>
        document.getElementById('btn').addEventListener('click', function (e) {
            document.getElementById('tiger').innerText = `&#129409;`;
        });
    </script>
</body>
</html>

But it doesn't work and shows just &#129409; instead of emoji when click button. Why is that, how can I set emoji dynamically?

This is what my html code looks like:

<html>
<style>
    body {
        font-size: 18px;
    }
</style>
<body>
    <span id="tiger" style='font-size:100px;'>&#128161;</span>
    <button id="btn">SET TIGER</button>

    <script>
        document.getElementById('btn').addEventListener('click', function (e) {
            document.getElementById('tiger').innerText = `&#129409;`;
        });
    </script>
</body>
</html>

But it doesn't work and shows just &#129409; instead of emoji when click button. Why is that, how can I set emoji dynamically?

Share Improve this question asked Mar 24, 2020 at 10:35 O. ShekriladzeO. Shekriladze 1,5363 gold badges23 silver badges47 bronze badges 1
  • “Why is that” - because you are not aware of the difference between innerText and innerHTML …? &#129409; only means “numeric HTML character reference” in an HTML context. In a text context, it is just that - text. – C3roe Commented Mar 24, 2020 at 10:46
Add a ment  | 

2 Answers 2

Reset to default 7

HTML Escapes

HTML escapes like "&#128161;" are decoded by the HTML parser when the source document is being parsed.

To set the content of a text node, use a JavaScript string - which technically is encoded in UTF-16.

JavaScript Strings

If you knew the hexadecimal representation of the character in UTF-16 you could set text node content using an escaped string like

element.textContent = "\ud83d\udca1"; // not remended.

If you knew the Unicode value in hex or decimal you could use the static String fromCodePoint method:

 element.textContent = String.fromCodePoint( 0x1f4a1) // or
 element.textContent = String.fromCodePoint( 128161 )

Another choice is to escape a 6 hex character code using a unicode escape with curly braces in JavaScript:

 element.textContent = '\u{01f4a1}'; // still not remended

However, the method I would remend is to encode the HTML file in UTF-8 when saving and set the text content with a standard string value in code:

 element.textContent = '
发布评论

评论列表(0)

  1. 暂无评论