TextBox按键事件不会在Google地图信息窗口内触发

时间:2012-04-07 06:39:50

标签: javascript jquery google-maps

我尝试在Google地图信息窗口内的TextBox上只允许有效字符。 'keypress'事件不是火灾。请帮我解决这个问题。

google.maps.event.addListener(drawingManager, 'polygoncomplete', function(polygon) {

        var polylength=polygon.getPath().getArray().length;
        var lastarray=polygon.getPath().getAt(polylength-1);

            vertex=polygon.getPath().getArray();
        var contentString="<form id='myform'>Name:<input name='cname' id='cname' type='text' size='50'></input><br>Address<input name='addr' id='addr' type='text' size='50'></input><br><input type='button' value='submit' onclick='save();'></input></form>";
        infowindow = new google.maps.InfoWindow({
            content: contentString,
            });
        infowindow.setPosition(lastarray);
        infowindow.open(map);
    }); 

$('input').bind('keypress', function(event){
                 alert("pressed");
                var regex = new RegExp("^[a-zA-Z0-9 ]+$");
                var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
                if (!regex.test(key)) {
                   event.preventDefault();
                   return false;
                }
        });

1 个答案:

答案 0 :(得分:2)

bind事件监听器input字段时,input字段尚未创建。您需要在infowindow上添加domready事件监听器},然后bind keypress听众:

infowindow = new google.maps.InfoWindow({
     content: contentString,
});
google.maps.event.addListener(infowindow , 'domready', function(){
    $('#myform input').bind('keypress', function(event){
             alert("pressed");
            var regex = new RegExp("^[a-zA-Z0-9 ]+$");
            var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
            if (!regex.test(key)) {
               event.preventDefault();
               return false;
            }
    });
});