在HTML Body上编写JavaScript变量 [英] Write JavaScript variable on HTML Body
问题描述
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Google Maps JavaScript API v3 Example: Reverse Geocoding</title>
<link
href="https://developers.google.com/maps/documentation/javascript/examples/default.css"
rel="stylesheet" type="text/css" />
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var geocoder;
var variablejs;
geocoder = new google.maps.Geocoder();
var input = "41.021355,-96.020508";
var latlngStr = input.split(",", 2);
var lat = parseFloat(latlngStr[0]);
var lng = parseFloat(latlngStr[1]);
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({
'latLng': latlng
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
variablejs = results[0].formatted_address; * * //document.write(variablejs); Not working**
*
//window.location.href = "http://localhost/test2.php?ad="+ variablejs; Working*
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
}); * * document.write(variablejs); * * //writes undefined variable (not working)
</script>
</head>
<body></body>
</html>
部分( // document.write(variablejs);无法使用 ),不会写变量variablejs,但是当我使用方法( // window.location.href =http://localhost/test2.php?ad =+ variablejs; Working ),它会写入url并转发传递该变量的页面作为参数。我想要做的是在同一个HTML的主体中打印该变量。
我试图首先初始化变量,然后写入主体,但看起来像该部分不能像全局变量或类似的东西那样访问。请帮忙。
The section (//document.write(variablejs); Not working), won't write the variable "variablejs", but when I use the method (//window.location.href = "http://localhost/test2.php?ad="+ variablejs; Working), it will write the url and forward the page passing the variable as a parameter. What I want to do is print that variable in the body of the same HTML. I tried to initialize first the variable then write into the Body but It looks like that section is not accessible like a global variable or something like that. Please help.
推荐答案
文档加载后,不能使用 document.write $ c $没有覆盖一切。您将需要操作DOM,例如
document.body.innerText = variablejs;
。但我建议您
Once the document is loaded, you can't use document.write
without overwriting everything. You will need to manipulate the DOM, e.g. document.body.innerText=variablejs;
. But I'd recommend
var d = document.createElement("div");
d.appendChild(document.createTextNode(variablejs));
document.body.appendChild(d);
这篇关于在HTML Body上编写JavaScript变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!