在下面的代码中,我使用jQuery调用来阻止回复到aspx页面,即调用Google地图以获取客户指示。当我使用回车键而不是" Directions"按钮。页面刷新。我已经包含了一些jQuery,它应该将按键功能与按钮本身联系起来,但它仍然会导致回发。
我的问题是,我可以通过将按键功能绑定到该按钮来阻止回复此代码吗?
编辑1:我仍然需要允许用户按下回车键来执行搜索路线。
jQuery的:
<script>
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var mapOptions = {
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: new google.maps.LatLng(31.320574, -85.70925),
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('directions-panel'));
var control = document.getElementById('control');
control.style.display = 'block';
map.controls[google.maps.ControlPosition.TOP].push(control);
var image = '../images/flag.png';
var marker = new google.maps.Marker({
position: new google.maps.LatLng(31.239661, -85.499698),
map: map,
icon: image
});
}
function calcRoute() {
var start = document.getElementById('txtAddress1').value;
var end = "business location";
var request = {
origin: start,
destination: end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
document.getElementById('map-canvas').style.display = 'inline-block';
}
$(document).ready(function () {
$("form input").keypress(function (e) {
if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
$('input[type=button] .NavButton').click();
return true;
}
});
});
google.maps.event.addDomListener(window, 'load', initialize);
</script>
相关HTML:
<div id="control">
<input type="text" id="txtAddress1" onchange="calcRoute()" value="" style="width: 300px; margin-top:40px; left:10px !important" />
<input class="NavButton" type="button" value="Get Directions" onclick="calcRoute()" />
</div>
答案 0 :(得分:1)
返回false
而非true
...或使用e.preventDefault()
表单中有提交按钮时enter
的默认操作是提交表单
当您返回true
时,默认操作会继续,但在您返回false
或使用e.preventDefault()