简体   繁体   English

Javascript在两个地方创建元素

[英]Javascript create elements in two places

How would I need to write this to have the elements created in two places? 我怎么需要写这个以在两个地方创建元素?

Here is my code. 这是我的代码。

I have tried using document.getElementsByName and document.getElementsByClassName and neither of them work. 我已经尝试使用document.getElementsByNamedocument.getElementsByClassName ,但它们都不起作用。

HTML HTML

<p style="display:block;" class="coords"></p>

Javascript 使用Javascript

function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    } else {
        x.innerHTML = "Geolocation is not supported by this browser.";
    }
}

function showPosition(position, coords)
{
    var places = document.getElementsByClassName(coords);
    for (var i = 0; i < places.length; i++)
    {
        places[i].innerHTML = "<input type='text' name='lat' id='lat' value='" + position.coords.latitude + "'>" +
            "<input type='text' name='lon' id='lon' value='" + position.coords.longitude + "'>";
    }
}

After calling getElementsByClassName you must use a loop to update each of them. 在调用getElementsByClassName ,必须使用循环来更新它们中的每一个。

function showPosition(position) {
    var places = document.getElementsByClassName("coords");
    for (var i = 0; i < places.length; i++) {
        places[i].innerHTML="<input type='text' name='lat' id='lat' value='" + position.coords.latitude + "'>" +
                            "<input type='text' name='lon' id='lon' value='" + position.coords.longitude + "'>";
    }
}

You may want to use 你可能想用

document.getElementsByClassName or document.getElementsByName document.getElementsByClassNamedocument.getElementsByName

with no capital letter at the start 一开始没有大写字母

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM