#javascript #html
#язык JavaScript #HTML
Вопрос:
lt;!DOCTYPE htmlgt; lt;htmlgt; lt;headgt; lt;titlegt; Location Test lt;/titlegt; lt;link rel="shortcut icon" href="#"gt; lt;/headgt; lt;bodygt; lt;h1gt; Location lt;/h1gt; lt;label id = "Address"gt; lt;/labelgt; lt;brgt; lt;input type="button" value="Log Out" id="LogOut"gt; lt;scriptgt; const logoutButton = document.getElementById("LogOut"); function getLocation() { navigator.geolocation.getCurrentPosition( function(Position) { var currentdate = new Date(); document.getElementById("Address").innerHTML = document.getElementById("Address").textContent "Last Sync: " currentdate.getDate() "/" (currentdate.getMonth() 1) "/" currentdate.getFullYear() ". " currentdate.getHours() ":" currentdate.getMinutes() "." currentdate.getSeconds() ". "; document.getElementById("Address").innerHTML = document.getElementById("Address").textContent "Latitude: " Position.coords.latitude; document.getElementById("Address").innerHTML = document.getElementById("Address").textContent " Longitude: " Position.coords.longitude; document.getElementById("Address").innerHTML = document.getElementById("Address").textContent " Accuracy: " Position.coords.accuracy; document.getElementById("Address").innerHTML = document.getElementById("Address").textContent " Heading towards direction: " Position.coords.heading; document.getElementById("Address").innerHTML = document.getElementById("Address").textContent " Speed: " Position.coords.speed; var api_key = '206170168bcf4fdf905d85a34f7b3d79'; var latitude = Position.coords.latitude; var longitude = Position.coords.longitude; var api_url = 'https://api.opencagedata.com/geocode/v1/json' var request_url = api_url '?' 'key=' api_key 'amp;q=' encodeURIComponent(latitude ',' longitude) 'amp;pretty=1' 'amp;no_annotations=1'; var request = new XMLHttpRequest(); request.open('GET', request_url, true); request.onload = function() { if (request.status === 200) { // Success! var data = JSON.parse(request.responseText); document.getElementById("Address").innerHTML = document.getElementById("Address").textContent " Address: " data.results[0].formatted; // print the location } else if (request.status lt;= 500) { // We reached our target server, but it returned an error console.log("unable to geocode! Response code: " request.status); var data = JSON.parse(request.responseText); console.log('error msg: ' data.status.message); } else { console.log("server error"); } }; request.onerror = function() { console.log("unable to connect to server"); }; request.send(); // make the request }, function(PositionError) { document.getElementById("Latitude").innerHTML = "Could not get latitude"; document.getElementById("Longitude").innerHTML = "Could not get longitude"; }) } getLocation(); setInterval(getLocation, 1000 * 5) logoutButton.addEventListener("click", (e) =gt; { e.preventDefault(); getLocation(); window.location.href = "login.html"; }) lt;/scriptgt; lt;/bodygt; lt;/htmlgt;
Этот код должен отображать координаты пользователя, направление, адрес и т.д. Затем через каждые 5 минут он повторяет это. Когда они выходят из системы, он делает это в последний раз. У меня есть одна метка для отображения адресов. Так что давайте предположим, что это
Last Sync: 5/12/2021. 14:13.28. Latitude: xxx Longitude: -xxx Accuracy: 13.454 Heading towards direction: null Speed: null Address: xxxxxxxxxxxxx
Я хочу, чтобы он постоянно печатал это:
Last Sync: 5/12/2021. 14:13.28. Latitude: xxx Longitude: -xxx Accuracy: 13.454 Heading towards direction: null Speed: null Address: xxxxxxxxxxxxx Last Sync: 5/12/2021. 14:13.28. Latitude: xxx Longitude: -xxx Accuracy: 13.454 Heading towards direction: null Speed: null Address: xxxxxxxxxxxxx Last Sync: 5/12/2021. 14:13.28. Latitude: xxx Longitude: -xxx Accuracy: 13.454 Heading towards direction: null Speed: null Address: xxxxxxxxxxxxx
Вместо этого я получаю
Last Sync: 5/12/2021. 14:13.28. Latitude: xxx Longitude: -xxx Accuracy: 13.454 Heading towards direction: null Speed: null Address: xxxxxxxxxxxxx Last Sync: 5/12/2021. 14:13.28. Latitude: xxx Longitude: -xxx Accuracy: 13.454 Heading towards direction: null Speed: null Address: xxxxxxxxxxxxx Last Sync: 5/12/2021. 14:13.28. Latitude: xxx Longitude: -xxx Accuracy: 13.454 Heading towards direction: null Speed: null Address: xxxxxxxxxxxxx
Комментарии:
1. Самым простым, но не каноническим ответом было бы добавить lt;brgt; в конец строки
2.
n
не имеет никакого эффекта в aninnerHTML
. И.textContent
удалит HTML-код.3. Куда мне добавить lt;brgt;? Я пытался
4. @Начинающий программист
document.getElementById("Address").innerHTML = document.getElementById("Address").textContent " Address: " data.results[0].formatted "lt;brgt;"; // print the location
5. Также измените
document.getElementById("Address").textContent "Last Sync: "
наinnerHTML
вместоtextContent
Ответ №1:
Вам не нужно вызывать document.getElementById(«Адрес»).textContent каждый раз, когда вы хотите добавить какой-либо текст к содержимому элемента адреса. Вы можете легко использовать element.innerHTML = «некоторое новое содержимое» и в конце каждой итерации добавлять тег br, чтобы создать новую строку. Приведенный ниже код должен работать для вас.
lt;!DOCTYPE htmlgt; lt;htmlgt; lt;headgt; lt;titlegt; Location Test lt;/titlegt; lt;link rel="shortcut icon" href="#"gt; lt;/headgt; lt;bodygt; lt;h1gt; Location lt;/h1gt; lt;label id = "Address"gt; lt;/labelgt; lt;brgt; lt;input type="button" value="Log Out" id="LogOut"gt; lt;scriptgt; const logoutButton = document.getElementById("LogOut"); function getLocation() { navigator.geolocation.getCurrentPosition( function(Position) { var currentdate = new Date(); document.getElementById("Address").innerHTML = "Last Sync: " currentdate.getDate() "/" (currentdate.getMonth() 1) "/" currentdate.getFullYear() ". " currentdate.getHours() ":" currentdate.getMinutes() "." currentdate.getSeconds() ". "; document.getElementById("Address").innerHTML = "Latitude: " Position.coords.latitude; document.getElementById("Address").innerHTML = " Longitude: " Position.coords.longitude; document.getElementById("Address").innerHTML = " Accuracy: " Position.coords.accuracy; document.getElementById("Address").innerHTML = " Heading towards direction: " Position.coords.heading; document.getElementById("Address").innerHTML = " Speed: " Position.coords.speed; var api_key = '206170168bcf4fdf905d85a34f7b3d79'; var latitude = Position.coords.latitude; var longitude = Position.coords.longitude; var api_url = 'https://api.opencagedata.com/geocode/v1/json' var request_url = api_url '?' 'key=' api_key 'amp;q=' encodeURIComponent(latitude ',' longitude) 'amp;pretty=1' 'amp;no_annotations=1'; var request = new XMLHttpRequest(); request.open('GET', request_url, true); request.onload = function() { if (request.status === 200) { // Success! var data = JSON.parse(request.responseText); document.getElementById("Address").innerHTML = " Address: " data.results[0].formatted; // print the location document.getElementById("Address").innerHTML = "lt;br/gt;"; } else if (request.status lt;= 500) { // We reached our target server, but it returned an error console.log("unable to geocode! Response code: " request.status); var data = JSON.parse(request.responseText); console.log('error msg: ' data.status.message); } else { console.log("server error"); } }; request.onerror = function() { console.log("unable to connect to server"); }; request.send(); // make the request }, function(PositionError) { document.getElementById("Latitude").innerHTML = "Could not get latitude"; document.getElementById("Longitude").innerHTML = "Could not get longitude"; }) } getLocation(); setInterval(getLocation, 1000) logoutButton.addEventListener("click", (e) =gt; { e.preventDefault(); getLocation(); window.location.href = "login.html"; }) lt;/scriptgt; lt;/bodygt; lt;/htmlgt;