下面的代码(示例不工作未包含库)计算两个坐标之间的距离,但在我的情况下此代码只执行一个表单(firs),例如如果在页面上有多个表单,则此代码将不会计算第二种形式,如何推动此代码计算所有表单,例如我在页面上有超过100个表单。
谢谢你。
document.addEventListener('DOMContentLoaded',function() {
const lat1 = document.querySelector('#lat1').value;
const lon1 = document.querySelector('#lon1').value;
const lat2 = document.querySelector('#lat2').value;
const lon2 = document.querySelector('#lon2').value;
const p1 = new LatLon(Dms.parseDMS(lat1), Dms.parseDMS(lon1));
const p2 = new LatLon(Dms.parseDMS(lat2), Dms.parseDMS(lon2));
const dist = parseFloat(p1.distanceTo(p2).toPrecision(4));
document.querySelector('#result-distance').textContent = dist;
});

<form>
Lat 1: <input type="hidden" name="lat1" id="lat1" value="25.434345" >
Lon 1: <input type="text" name="lon1" id="lon1" value="55.902223445" >
Lat 2: <input type="text" name="lat2" id="lat2" value="25.8944324" >
Lon 2: <input type="text" name="lon2" id="lon2" value="55.893445">
<output id="result-distance"></output> metres
</form>
&#13;
答案 0 :(得分:0)
你遇到了问题,因为如果你在你的页面中添加两个form
具有相同的元素ID,它总是引用最后一个,这就是问题。
解决方案是尝试给id形成比获取该表单的子输入元素并执行计算。
你可以这样做
var children = el.getElementsByTagName('fromid');
for(var i = 0; i< children.length;i++)
{
if (children[i].getAttribute('id') == 'child')
{
// do what ever you want with the element..
// children[i] holds the element at the moment..
}
}