我试图找到城市和国家,并在标记字段中插入信息作为值。 尝试了几个选项,没有一个对我有用,原始代码成功地将信息插入元素,但这不是我需要的。
我尝试为输入标记提供ID名称,并将文字插入内部,如下所示:$('#country')。value(fulladd [count-1]); 但它没有奏效,输出是
<input type="text" tabindex="3" name="city">Whatever</input>
function locate() {
var location = document.getElementById("location");
var apiKey = 'f536d4c3330c0a1391370d1443cee848';
var url = 'https://api.forecast.io/forecast/';
navigator.geolocation.getCurrentPosition(success, error);
function success(position) {
latitude = position.coords.latitude;
longitude = position.coords.longitude;
$.getJSON("http://maps.googleapis.com/maps/api/geocode/json?latlng="+latitude + "," + longitude + "&language=en", function(data) {
var fulladd = data.results[0].formatted_address.split(",");
var count= fulladd.length;
$('#country').text(fulladd[count-1]);
$('#city').text(fulladd[count-2]);
});
}
function error() {
location.innerHTML = "Unable to retrieve your location";
}
$('#country').text('Locating...')
}
locate();
&#13;
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="style.css" />
<title> Locating </title>
</head>
<body>
<form id="form1">
<div class="registration_form">
<section id="location">
<div id="country">
<label>
Country<br><input type="text" tabindex="3" value="0"
name="country" >
</label>
</div>
<div id="city">
<label>
City<br><input type="text" tabindex="3" name="city">
</label>
</div>
<div>
</section>
</div>
</form>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="app.js"></script>
</html>
&#13;
答案 0 :(得分:0)
你有两个问题:
修正HTML:
<div id="country">
<label>Country</label>
<input id="countryInput" type="text" tabindex="3" name="country">
</div>
<div id="city">
<label>City</label>
<input id="cityInput" type="text" tabindex="3" name="city">
</div>
并修复了JS:
function locate() {
var location = document.getElementById("location");
var apiKey = 'f536d4c3330c0a1391370d1443cee848';
var url = 'https://api.forecast.io/forecast/';
navigator.geolocation.getCurrentPosition(success, error);
function success(position) {
latitude = position.coords.latitude;
longitude = position.coords.longitude;
$.getJSON("http://maps.googleapis.com/maps/api/geocode/json?latlng="+latitude + "," + longitude + "&language=en", function(data) {
var fulladd = data.results[0].formatted_address.split(",");
var count= fulladd.length;
$('#countryInput').val(fulladd[count-1]);
$('#cityInput').val(fulladd[count-2]);
});
}
function error() {
location.innerHTML = "Unable to retrieve your location";
}
}