assigning html entity code in javascript button not working

送分小仙女□ 提交于 2021-01-29 21:15:10

问题


I am trying to create a button in javascript and assigning HTML entity code ⛨ to it. This is the HTML entity code of down arrow. Instead of showing the down arrow, the entire code is displayed in the button as is.

Below is how i am trying to achieve it

<!DOCTYPE html>
<html>
    <head></head>
    <body>
    <script type="text/javascript">
        var btn = document.createElement("input");
        btn.setAttribute('type','button');
        btn.setAttribute('value','&#9660;');
        document.body.appendChild(btn);
    </script>
    </body>
</html>

Below is the output of my code

I expect that the button should display down arrow but for some reason it is not showing.


回答1:


You should use innerHTML instead of setAttribute:

var btn = document.createElement("input");
btn.setAttribute('type','button');
btn.innerHTML = '&#9960;';
document.body.appendChild(btn);

http://jsfiddle.net/dapx0nsy/




回答2:


Try replacing &#9960; with \u26E8, try \u2193 for down arrow. JsFiddle, ref

<!DOCTYPE html>
<html>
    <head></head>
    <body>
    <script type="text/javascript">
        var btn = document.createElement("input");
        btn.setAttribute('type','button');
        btn.setAttribute('value','\u26E8');
        document.body.appendChild(btn);
        btn = document.createElement("input");
        btn.setAttribute('type','button');
        btn.setAttribute('value','\u2193');
        document.body.appendChild(btn);
    </script>
    </body>
</html>



回答3:


Try like this,

<html>
    <head></head>
    <body>
    <button>&#9960;</button>
    <script type="text/javascript">
        var btn = document.createElement("input");
        btn.setAttribute('type','button');
        btn.setAttribute('value','\u26E8');
        document.body.appendChild(btn);
    </script>
    </body>
</html>

First button from DOM, Second one from Script.



来源:https://stackoverflow.com/questions/56526299/assigning-html-entity-code-in-javascript-button-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!