[英]How to add an array element to html with jQuery
我使用浏览器的内置导航器创建了一个包含两个元素的数组。 gpsLocation[0]
是我的纬度,而gpsLocation 1是我的经度。 在我的jQuery代码之前,立即使用log检查我的gpsLocation,我确认两个值都存在。 但是,当我将数组的第一个元素分配给段落元素的html时,它表示未定义。 我什至检查了它给我的坐标,它们的准确性令人震惊。 我一直在寻找答案,有一百万个措辞相似的问题,但似乎没有一个人试图这样做。
这是我的代码:
function getLocation() { var gpsLocation = []; if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position) { gpsLocation.push(position.coords.latitude); gpsLocation.push(position.coords.longitude); }); } return gpsLocation; } function getWeather() { var gpsLocation = getLocation(); console.log(gpsLocation);//Looks good in the console. $(function(){ $('#test-paragraph').html('Latitude: ' + gpsLocation[0]); }); }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="weather"> <button id="test-button" onclick="getWeather()">Test Button</button> <p id="test-paragraph">This is a sample paragraph for learning jQuery</p> </div>
第二个函数名称似乎是随机的,但最终将取决于天气。 仍在努力理解jQuery和json。
function getLocation() { var gpsLocation = []; if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position) { var pos = { latitude: "a", longitude: "v" }; gpsLocation.push(pos); }); } return gpsLocation; } function getWeather() { var gpsLocation = getLocation(); console.log(gpsLocation); //Looks good in the console. $(function() { $('#test-paragraph').html('Latitude: ' + gpsLocation[0]); }); }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="weather"> <button id="test-button" onclick="getWeather()">Test Button</button> <p id="test-paragraph">This is a sample paragraph for learning jQuery</p> </div>
您没有执行navigator.geolocation.getCurrentPosition(function(position)函数,这意味着var gpsLocation保持为空数组。运行我的编辑,查看日志“ now in here”从不触发,请首先调查该问题。
function getLocation() { var gpsLocation = []; if (navigator.geolocation) { console.log('in here'); navigator.geolocation.getCurrentPosition(function(position) { console.log('now in here'); var pos = [{ latitude: "a", longitude: "v" }]; gpsLocation.push(pos); console.log('do i get this far?'); }); } return gpsLocation; } function getWeather() { var gpsLocation = getLocation(); console.log(gpsLocation); //Looks good in the console. $(function() { $('#test-paragraph').html('Latitude: ' + gpsLocation[0]); }); }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="weather"> <button id="test-button" onclick="getWeather()">Test Button</button> <p id="test-paragraph">This is a sample paragraph for learning jQuery</p> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.