有没有办法让下面的脚本将javascript值传递给href链接的url?
<script type="text/javascript">
function geoPreview(lat,long) {
var elemA = document.getElementById("lat").value;
var elemB = document.getElementById("long").value;
window.location.href = "http://www.gorissen.info/Pierre/maps/googleMapLocation.php?lat=elemA&lon=elemB&setLatLon=Set";
}
</script>
答案 0 :(得分:32)
试试这个:
window.location.href = "http://www.gorissen.info/Pierre/maps/googleMapLocation.php?lat="+elemA+"&lon="+elemB+"&setLatLon=Set";
要将变量放在字符串中,请将变量括在引号和附加符号中,如下所示:
var myname = "BOB";
var mystring = "Hi there "+myname+"!";
请记住一条规则!
答案 1 :(得分:3)
您的意思是在URL的查询字符串中包含javascript变量值吗?
是:
window.location.href = "http://www.gorissen.info/Pierre/maps/googleMapLocation.php?lat="+var1+"&lon="+var2+"&setLatLon="+varEtc;
答案 2 :(得分:1)
具有字符串串联或字符串内插(通过模板文字)。
此处包含JavaScript模板文字:
function geoPreview() {
var lat = document.getElementById("lat").value;
var long = document.getElementById("long").value;
window.location.href = `http://www.gorissen.info/Pierre/maps/googleMapLocation.php?lat=${lat}&lon=${long}&setLatLon=Set`;
}
这两个参数都未使用,可以删除。
使用+
运算符连接字符串:
window.location.href = "http://www.gorissen.info/Pierre/maps/googleMapLocation.php?lat=" + elemA + "&lon=" + elemB + "&setLatLon=Set";
有关更简洁的代码,请使用JavaScript 模板文字以字符串表示形式替换表达式。
模板文字用``
括起来,占位符用${}
括起来:
window.location.href = `http://www.gorissen.info/Pierre/maps/googleMapLocation.php?lat=${elemA}&lon=${elemB}&setLatLon=Set`;
自ECMAScript 2015(ES6)起可用的模板文字。
答案 3 :(得分:-1)
试试这个:
window.location.href = "http://www.gorissen.info/Pierre/maps/googleMapLocation.php?lat=\''+elemA+'\'&lon=\''+elemB+'\'&setLatLon=Set";
答案 4 :(得分:-1)
这太复杂了,但是对没有经验的程序员是有意义的。在网址中,您可以添加“#”号,之后只要转到该页面,其他任何内容都可以。因此,您可以使用js:
Var pass = prompt(“what do you want to pass”)
Var site = “google.com”
Var readysite = site + pass
Document.location.replace(readysite)
然后在另一页中,使用JavaScript读取URL并获取必要的信息。
注意:上面的js未经过测试。