如何在innerHTML中添加超链接?

时间:2017-04-14 20:24:02

标签: javascript

<!DOCTYPE html>
<html style="height: 99%;">
<meta charset=utf-8>
<body style="height: 99%;">
    <table style="height: 99%;" align=center>
        <tr>
            <td>
                <p id="sample" style="font-size:300%"></p>
                <script>
                    var myArray = [
                        'first',
                        'second',
                        'third',
                        'fourth'
                    ];
                    var rand = Math.floor(Math.random() * myArray.length)
                    var concat = myArray[rand]
                    concat = '&lt;a href=https://www.google.com/#q='+concat+'&gt;'+concat+'&lt;/a&gt;'
                    function random() {
                        document.getElementById("sample").innerHTML = (concat);
                    }
                    random()
                </script>
            </td>
        </tr>
    </table>
</body>
</html>

看起来像这样:https://i.stack.imgur.com/NvgQo.png

问:如何让超链接工作?

它只显示html代码

1 个答案:

答案 0 :(得分:1)

变化:

concat = '&lt;a href=https://www.google.com/#q='+concat+'&gt;'+concat+'&lt;/a&gt;'

要:

concat = '<a href=https://www.google.com/#q=' + concat + '>' + concat + '</a>'