Я хочу вставить значение переменной 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);
    }
});

Что я делаю не так?

0
Ballistic Swami 23 Окт 2019 в 20:46

2 ответа

В вашем HTML удалите script и создайте span с id, затем нацелите innerText диапазона.

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

Тогда в вашем JS,

document.getElementById('dynamic-value').innerText = regno
0
JDunken 23 Окт 2019 в 21:16

Возможно, вы хотите сохранить весь 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;
    }
});
0
Sammy Tang 23 Окт 2019 в 21:58
Разве ты не скучаешь по myElement.append(newcontent)?
 – 
JDunken
23 Окт 2019 в 21:12