简体   繁体   English

Javascript等同于变量.value

[英]Javascript Equating Variable .value

This is the code I'm working from: http://jsfiddle.net/9B84H/26/ 这是我正在使用的代码: http : //jsfiddle.net/9B84H/26/

function autosuggest() {
var input = document.getElementById('location');
    var options = {types: [],};
    var autocomplete = new google.maps.places.Autocomplete(input, options);
}

function getLatLng() {
    var geocoder = new google.maps.Geocoder();
    var address = document.getElementById('location').value;
    geocoder.geocode({
        'address': address
    }, function (results, status) {
        if (status === google.maps.GeocoderStatus.OK) {
            $('#lat').val(results[0].geometry.location.lat());
            $('#lng').val(results[0].geometry.location.lng());
        } else {
            alert("Geocode failed: " + status);
        }
    });
}

There are two variables which are pretty much the same​: 有两个几乎相同的变量:

var address = document.getElementById('location').value;
var input = document.getElementById('location');

Is there any opportunity to combine this into one line as a global variable? 是否有机会将其作为一个全局变量组合成一行?

You could use your anonymous self invoking function or just use the dom-ready method in jQuery to wrap your code (dom-ready seems like a better idea if you don´t put your JS code at the bottom of the page). 您可以使用匿名的自我调用功能,也可以只在jQuery中使用dom-ready方法来包装代码(如果不将JS代码放在页面底部,则准备好dom-ready似乎是一个更好的主意)。

I did an example removing the onclick, onfocus attribute on your input and put them in the javascript section: http://jsfiddle.net/9B84H/27/ 我做了一个示例,删除输入上的onclick,onfocus属性,并将其放在javascript部分中: http : //jsfiddle.net/9B84H/27/

$(function() {
    var location = document.getElementById('location');
    var getLatLng = function() {
        var geocoder = new google.maps.Geocoder();
        var address = location.value;
        geocoder.geocode({
            'address': address
        }, function (results, status) {
            if (status === google.maps.GeocoderStatus.OK) {
                $('#lat').val(results[0].geometry.location.lat());
                $('#lng').val(results[0].geometry.location.lng());
                alert("Geocode success");
            } else {
                alert("Geocode failed: " + status);
            }
        });
    };
    var autosuggest = function() {
        var options = {types: []};
        var autocomplete = new google.maps.places.Autocomplete(location, options);
    };
    $("#location").on("focus", autosuggest);
    $(":button[name='Geocode']").on("click", getLatLng);
});

you now have a local variable named location that reference the #location element in your document. 您现在有了一个名为location的局部变量,该变量引用了文档中的#location元素。

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

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