使onclick功能与ENTER一起工作;Go"Safari Mobile(iOS)上的按钮

Make onclick function work with ENTER and "Go" button on Safari Mobile (iOS)

本文关键字:Mobile Safari iOS 按钮 quot 功能 onclick ENTER 一起 Go 工作      更新时间:2023-09-26

我有一个表单,其中按钮调用函数onclick:

<form>
    <input type="text" id="start" name="start">
    <input type="button" onclick="calcRoute();" value="Go">
</form>
function calcRoute() {
    var start = document.getElementById('start').value;
      var end = "My Address in Rome";
      var request = {
        origin:start,
        destination:end,
        travelMode: google.maps.DirectionsTravelMode.TRANSIT
      };
    directionsService.route(request, function(response, status) {
      if (status == google.maps.DirectionsStatus.OK) {
        directionsDisplay.setDirections(response);
      }
    });
}

如果单击Go按钮(<input type="button">(,它在每个浏览器上都能正常工作。如果我填充<input type="text">并在键盘上按ENTER(例如,在iOS键盘中按GoNTER,它就会工作。我怎么能让它也这样工作呢?

编辑:请不要使用jQuery或其他框架。:(

您实际上应该删除该内联javascript,并将该按钮变成一个真正的提交按钮。之后,您可以轻松地捕获正在提交的表单(无论是输入键还是通过提交按钮(:

form.addEventListener('submit', calcRoute);

演示:http://jsfiddle.net/ghK4P/

试试这个:

<form onsubmit="calcRoute()">
    <input type="text" id="start" name="start">
    <input type="button" onclick="calcRoute();" value="Go">
</form>

我相信它能同时适用于

如果使用jquery ,可能会将其添加到代码中

$(document).ready(function() {
$("#start").bind('keyup',function(event){
    if(event.keyCode == 13){
        $("#start").click();
    }
});
});

按下文本框中的回车键,它将触发您的按钮点击功能。

如果你不使用jquery,试试这个

<input type="text" id="start" name="start" onkeydown="if (event.keyCode == 13) document.getElementById('fire_calRoute').click()">
<input type="button" id='fire_calRoute' onclick="calcRoute();" value="Go">

试试这个,希望它能解决你的问题。

<input type="text" id="start" name="start" onkeypress="return calcRoute(event)">

现在修改你的脚本如下:

function calcRoute(e) {
    if (e.keyCode == 13) {
        //your code
    }
}

我找到了解决方案:(

<form onsubmit="calcRoute(); return false">
    <input type="text" id="start" name="start">
    <input type="submit" value="Vai">
</form>