通过指定键函数输入键javascript来防止回发
在下面的代码中,我使用jQuery调用来阻止在aspx页面上发回帖子,即调用googlemaps获取客户指示。当我使用回车键而不是方向按钮时。页面刷新。我已经包含了一点jQuery,它应该将按键功能绑定到按钮本身,但它仍然会导致post返回 我的问题是,我可以通过将按键功能绑定到该按钮来防止在代码中发回post吗 编辑1:我仍然需要能够允许用户按enter键执行方向搜索 jQuery:通过指定键函数输入键javascript来防止回发,javascript,jquery,asp.net,webforms,Javascript,Jquery,Asp.net,Webforms,在下面的代码中,我使用jQuery调用来阻止在aspx页面上发回帖子,即调用googlemaps获取客户指示。当我使用回车键而不是方向按钮时。页面刷新。我已经包含了一点jQuery,它应该将按键功能绑定到按钮本身,但它仍然会导致post返回 我的问题是,我可以通过将按键功能绑定到该按钮来防止在代码中发回post吗 编辑1:我仍然需要能够允许用户按enter键执行方向搜索 jQuery: <script> var directionDisplay; va
<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>
返回false而不是true。。。或者使用e.default
当表单中有提交按钮时,enter的默认操作是提交表单
当您返回true时,默认操作将继续,但当您返回false或使用e.preventDefault时,默认操作将不会继续。这似乎完全阻止了enter键功能的实际执行。我测试了您的答案,但在使用enter键时无法获取方向。听起来您在触发另一次单击或调用calcRoute Yourself之前阻止了它注意到$'input[type=button].NavButton'中有一个额外的空格。。。这是在寻找.Navbutton,它是。删除该空间将查找作为输入的.NavButton,此时它应为$'input[type=button].NavButton'。单击?工作很好,非常感谢你的澄清。