简体   繁体   中英

How to set emoji unicode 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?

 <html> <style> body { font-size: 18px; } </style> <body> <span id="tiger" style='font-size:100px;'>&#128161;</span> <button id="btn">SET TIGER</button> <script> var code = '129409'; // document.getElementById('btn').addEventListener('click', function (e) { document.getElementById('tiger').innerText = String.fromCodePoint(parseInt(code));; }); </script> </body> </html>

Kindly check below, Hope your query is resolved.

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

    <script>
    var code = '129409';
         //
        document.getElementById('btn').addEventListener('click', function (e) {
            document.getElementById('tiger').innerText = String.fromCodePoint(parseInt(code));;
        });
    </script>
</body>
</html>

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.

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

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

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

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

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

 element.innerText = '💡'

Limited code editor support for Unicode fonts makes this a bit difficult, of course.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM