JQuery val(),text()和html()都返回一个空字符串

时间:2014-12-21 18:01:30

标签: javascript jquery html

我有一个可能是小问题,但不知何故我无法修复它,因为我坐在这里2个小时没有修复。

我在服务器端使用node.js express,在客户端使用javascript / jQuery,使用jade作为HTML模板引擎,使用谷歌地图编写了一个小帮手工具。 我想通过用户输入动态调整我的google-maps-pins周围的GPS半径,但我总是将空字符串作为返回。

HTML:

<form id="formTrackedBus" action="/trackBus" method="post" name="trackedBus">
    <input id="asdf" type="text" placeholder="Type in radius around the bus">
    <button id="btnSubmit" onclick="getRadius()" value="submit" type="submit">submit</button>

调用getRadius();的jQuery部分如下所示:

$(document).ready(function () {      
    $(function getRadius(){
        var radius = $('#asdf').val();
        alert("Radius: "+radius);
    });
...  
});

enybody在这看到了问题吗? .text().html()也会返回空字符串。我真的没有弄错,我已经将id重命名为“asdf”,以确保它不是一个公开的身份......

更明确地说:

我正在处理$(document).ready - 块内的google-maps-stuff。在那里,我需要通过用户输入半径来动态调整我的标记的半径。

我首先尝试使用全局变量,看起来像这样

var radius;
function getRadius() {
    radius = document.getElementById('asdf');
    alert(radius.value); 
}

这很好用。但是,当我尝试在$(document).ready - 块中使用此全局 radius 时,由于每次都返回 undefined ,因此无法正常工作:

var radius;
function getRadius() {
    radius = document.getElementById('asdf');
    alert(radius.value); 
}

$(document).ready(function () {

$(function initialize() {
    var mapOptions = {
        // center Aachen at the map
        center: new google.maps.LatLng(50.7753455, 6.083886799999959),
        zoom: 12,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById('googleMap'), mapOptions);

    google.maps.event.addDomListener(window, 'load', initialize);
});

// doesn't look nice, but using setInterval(addMarker(), 5000); didn't work
// since curiously this way addMarker was just fired once...
setInterval(function addMarker() {

    var newLat = 0;
    var newLang = 0;


// jQuery AJAX call for JSON
        $.getJSON('/busdata/busCoordinates', function (data) {$.each(data, function () {
            var marker = new google.maps.Marker({
                position: new google.maps.LatLng(this.latitude, this.longitude),
                title: 'MarkerNo: '+pollingRound+'\n'+
                    'VehicleID: '+this.vehicleID.toString()+'\n'+
                    'Update Time:'+this.time
            });
            var busRadius;
            var circleOptions = {
                strokeColor: "FF0000",
                strokeOpacity: 0.5,
                strokeWeight: 2,
                fillColor: "#FF0000",
                fillOpacity: 0.35,
                map: map,
                center: new google.maps.LatLng(this.latitude, this.longitude),
                radius: radius
            };
    };

那么我如何才能在var radius中获得此circleOptions

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。 问题不在于代码本身,而在于程序流程。 每次当我点击提交时,我都会重新加载index.js,因此我的全局var radius会在我的网页重新加载后再次被其默认值覆盖。 因此,getRadius()已被调用,实际上覆盖全局val radius,但覆盖页面再次重新加载,因此radius已被重新加载之后用默认值再次覆盖。

无论如何,谢谢你的帮助!

相关问题