繁体   English   中英

在HTML主体上编写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正文中打印该变量。 我试图先初始化变量,然后将其写入主体,但看起来该部分无法像全局变量那样访问。 请帮忙。

加载文档后,如果不覆盖所有内容,则无法使用document.write 您将需要操作DOM,例如document.body.innerText=variablejs; 但我建议

var d = document.createElement("div");
d.appendChild(document.createTextNode(variablejs));
document.body.appendChild(d);

您要在传递给geocoder.geocode()的回调函数中为variablejs赋值。 这意味着您正在尝试在调用回调之前访问和编写它,因此您将看不到任何设置的值。

在这些情况下,使用Firebug或类似工具进行调试会有所帮助。

同样,在文档加载后,您不能再使用docuemnt.write这样的文件,而需要进行一些DOM操作。

暂无
暂无

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

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