无法将内部HTML设置为字符串变量

时间:2016-08-18 06:16:09

标签: javascript

我尝试过但无法将内部HTML设置为字符串变量。

以下是我正在尝试的完整代码。

虽然内部HTML的语法不是那么复杂但是无法修复它。

 <!DOCTYPE html>
    <html>
    <head>
        <title></title>
        <meta charset="utf-8" />
        <script type="text/javascript">
            var starDetailsString = "ali";
            var star = {};
            function Star(constell, type, specclass, magnitude) {
                this.constellation = constell;
                this.type = type;
                this.spectralClass = specclass;
                this.mag = magnitude;
            }
            star['Polaris'] = new Star("Ursa Minor", "Double/Cepheid", "F7", 2.0);
            star['Vega'] = new Star("Lyra", "White Dwarf", "A0 V", 0.03);
            star['Altair'] = new Star("Aquila", "White Dwarf", "A7 V", 0.77);
        </script>
    </head>
    <body>
        <script type="text/javascript">

            for (var element in star)
            {
                for (var prop in star[element]) {
                    starDetailsString += element + " : " + prop + " = " + star[element][prop];
                    starDetailsString += "<br/>";
                }
                starDetailsString += "<br/>";
            }
            document.getElementById('starDetails').innerHTML = starDetailsString;

        </script>
        <div id="starDetails">

        </div>
    </body>
    </html>

2 个答案:

答案 0 :(得分:1)

&#13;
&#13;
<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8" />

</head>
<body>
    <div id="starDetails">

    </div>

    <script type="text/javascript">
        var starDetailsString = "ali";
        var star = {};
        function Star(constell, type, specclass, magnitude) {
            this.constellation = constell;
            this.type = type;
            this.spectralClass = specclass;
            this.mag = magnitude;
        }
        star['Polaris'] = new Star("Ursa Minor", "Double/Cepheid", "F7", 2.0);
        star['Vega'] = new Star("Lyra", "White Dwarf", "A0 V", 0.03);
        star['Altair'] = new Star("Aquila", "White Dwarf", "A7 V", 0.77);

        for (var element in star)
        {
            for (var prop in star[element]) {
                starDetailsString += element + " : " + prop + " = " + star[element][prop];
                starDetailsString += "<br/>";
            }
            starDetailsString += "<br/>";
        }
        document.getElementById('starDetails').innerHTML = starDetailsString;

    </script>
</body>
</html>
&#13;
&#13;
&#13;

您的javascript在您要填充的div之前运行。将您的JavaScript移动到页面末尾。

答案 1 :(得分:0)

只需将<script>部分放在<div id="starDetails"></div>部分后面。