我有 6 个隐藏字段,用于保存 3 个不同邮政编码的纬度和经度:
<input type="hidden" id="geo_lat1" name="geo_lat1">
<input type="hidden" id="geo_lon1" name="geo_lon1">
<input type="hidden" id="geo_lat2" name="geo_lat2">
<input type="hidden" id="geo_lon2" name="geo_lon2">
<input type="hidden" id="geo_lat3" name="geo_lat3">
<input type="hidden" id="geo_lon3" name="geo_lon3">
我还有邮政编码的三个输入字段:
<input type="text" name="search_postcode1" id="search_postcode1">
<input type="text" name="search_postcode2" id="search_postcode2">
<input type="text" name="search_postcode3" id="search_postcode3">
我的地理编码功能工作正常,但仅适用于第一组纬度/经度。如果我想生成其他两个邮政编码的纬度/经度,我必须复制并粘贴每个邮政编码的地理编码函数,只需更改以下行中输入名称末尾的数字:
var sAddress1 =document.getElementById("search_postcode1").value ;
我不想复制/粘贴,而是想在循环中使用相同的代码,这意味着将引用从 search_postcode1 更改为 search_postcode2 和 search_postcode3
我知道我可以使用 join() 将数据连接到数组中并将其分配给另一个变量,如下所示:
var a = new Array("search_postcode","1");
var pcname = a.join(""); // pcname would be assigned "search_postcode1"
我的问题是如何分配它,以便它出现在上面的代码行中,而不是变量中的值?
<小时/>编辑
我还需要使用以下方法将其分配给隐藏字段:
geo_lat1.value = loc[0];
geo_lon1.value = loc[1];
如何将循环中的“1”更改为“2”和“3”?它一定是与 getElementById("search_postcode"+ "1") 方式不同的方式吗?
最佳答案
你可以这样做:
for (var i = 1; i <= 3; i++) {
var address = document.getElementById('search_postcode' + i);
// Do something with address. Each time through the loop, it will
// reference the "i" search_postcode input, 1-3. Maybe something like:
var loc = geoCodePostCode(address.value);
document.getElementById('geo_lat' + i).value = loc[0];
document.getElementById('geo_long' + i).value = loc[1];
}
关于javascript - 使用 join() 创建 HTML id?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21650268/