需要帮助将数据插入html

时间:2019-10-23 17:46:09

标签: javascript html firebase

我想将Javascript变量的值插入html文件。但是输出为空。所需的数据存储在变量中,但html文件中的输出为空白。

我的htmll文件

<div class="student-info">
     <p>Name: Anon</p>
     <p>Registration Number:</p>

<script src="resources/js/data_inp.js">document.write(regno)</script>
<script src="resources/js/data_inp.js"></script>

我的data_inp.js文件

//get regno
firebase.auth().onAuthStateChanged(function(user) {
    if (user) {
        console.log(user);
        var email = firebase.auth().currentUser.email;
        var regno = email.substring(0, email.length - 8);
        //email is eg. 1234@xyz.com where 1234 is regno so I used this method to separate the regno
        console.log(regno);
    }
});

我在做什么错了?

2 个答案:

答案 0 :(得分:0)

也许您想将所有javascript保留在一个文件中,并将所有html保留在一个文件中,并使用document.getElementById()定位特定元素

html

<div class="student-info">
                        <p>Name: Anon</p>
                        <p id=registrationNumber>Registration Number:</p>
</div>
<script src="resources/js/data_inp.js"></script>

javascript

//get regno
firebase.auth().onAuthStateChanged(function(user) {
    if (user) {
        console.log(user);
        var email = firebase.auth().currentUser.email;
        var regno = email.substring(0, email.length - 8);
        //email is eg. 1234@xyz.com where 1234 is regno so I used this method to separate the regno
        console.log(regno);

        var myElement = document.getElementById("registrationNumber");
        var newcontent = document.createElement('div');
        myElement.append(newcontent);
        newcontent.innerHTML = regno;
    }
});

答案 1 :(得分:0)

在您的HTML中,删除script,并用span制作一个id,然后指定跨度的innerText

<p>Registration Number: <span id="dynamic-value"></span></p>

然后在您的js中

document.getElementById('dynamic-value').innerText = regno