使用javascript,.innerHTML更改输入的值

时间:2015-01-20 14:55:06

标签: javascript html5 dom

我尝试获取用户位置,然后插入两个单独的<input>字段。尝试打印到<p id="lat"></p>时,该脚本有效。但不适用于<input>

<form>
    <input type="number" step="any" name="lat" id="lat" value="" />
    <input type="number" step="any" name="lng" id="lng" value="" />
</form>

<button onclick="getLocation()">Get current location</button>

<script>
    var x = document.getElementById("lat").value;
    var y = document.getElementById("lng").value;
    function getLocation() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(showPosition);
        } else {
            x.innerHTML = "Geolocation is not supported by this browser.";
        }
    }
    function showPosition(position) {
        x.innerHTML = position.coords.latitude;
        y.innerHTML = position.coords.longitude;
    }
</script>

我在这里缺少什么?已将.value添加到可靠的末尾,我想知道它是data类型和/或step值吗?

2 个答案:

答案 0 :(得分:3)

x没有innerHTML,因为x等于#lng元素中保存的字符串值。它不等于元素本身。

不是将xy设置为每个元素的value,而是将它们自己设置为元素:

var x = document.getElementById("lat");
var y = document.getElementById("lng");

然后,您可以使用x.valuey.valuex.innerHTMLy.innerHTML)设置值:

x.value = "Geolocation is not supported by this browser.";

function showPosition(position) {
    x.value = position.coords.latitude;
    y.value = position.coords.longitude;
}

答案 1 :(得分:1)

只需设置x.value= position.coords.latitude;

并删除初始化 x= document.getElementById("lat");

var x = document.getElementById("lat");
    var y = document.getElementById("lng");
    function getLocation() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(showPosition);
        } else {
            x.innerHTML = "Geolocation is not supported by this browser.";
        }
    }
    function showPosition(position) {
        x.value= position.coords.latitude;
        y.value= position.coords.longitude;
    }