【问题标题】:jquery - clicking vs hitting enter on form gives different results - why?jquery - 在表单上单击与按 Enter 会产生不同的结果 - 为什么?
【发布时间】:2013-11-19 07:48:46
【问题描述】:

我的页面上有一个简单的表单:

<form id="add_item_form" role="form">
  <input type="text" name="newitem" value="" id="new-item-input"/>
  <button type="button" id="new-item-button">go</button>
</form>

我有一些 JavaScript 用于捕获按钮单击或用户从文本输入中按 ENTER 键。这个想法是捕获 ENTER keyup 事件,然后以编程方式单击按钮。单击按钮时,应该发生一个 ajax 发布事件。这是 JavaScript:

$(function() {
  console.log('start');

  // give the focus to the text input
  $("#new-item-input").focus();

  // if the user hits enter in the text input, click the button
  $("#new-item-input").keyup(function(event){
    if(event.keyCode == 13){
      $("#new-item-button").click();
    }
  });

  // the callback function that is run if ajax succeeds
  var new_item_ajax_success = function(result) {
    console.log('success');
    $("#new-item-input").focus();
  }

  // the function that is run when the button is clicked
  var new_item_button_clicked = function() {
    console.log('new item button clicked!');
    $.post('/add_item/', {});
  }

  // add the function to the button
  $('#new-item-button').click(new_item_button_clicked);

  console.log('end');
});

我的期望是无论用户点击 ENTER 还是点击按钮,行为都应该是相同的。然而,事实并非如此。当用户按 ENTER 时,控制台日志如下:

new item button clicked!
start
end

另外,我的服务器日志记录了一个 GET 请求。我认为控制台日志中的startend 表示页面正在重新加载。

当用户点击按钮时,控制台日志如下:

new item button clicked!
POST http://localhost:8000/add_item/ 403 (FORBIDDEN)

另外,我的服务器日志记录了一个 POST 请求。 (预计会出现 403 错误。)

我的问题:为什么在这两种情况下我都没有得到预期的 POST 请求行为?

【问题讨论】:

  • 您可以使用key downkey press 事件处理hitting 事件

标签: javascript jquery ajax forms post


【解决方案1】:

在您的代码中,很明显,当您按下 Enter 键(即带有keyCode == 13 的键)时,将执行以下代码:

// if the user hits enter in the text input, click the button
$("#new-item-input").keyup(function(event){
  if(event.keyCode == 13){
    $("#new-item-button").click();
  }
});

同时,当您单击按钮时,还会执行另一个代码。

var new_item_button_clicked = function() {
  console.log('new item button clicked!');
  $.post('/add_item/', {});
}

许多浏览器(如 Internet Explorer)不遵循如下所示的代理事件:

$("#new-item-button").click();

因此,您可能会发现单击和按下 Enter 键是有区别的。我想这应该是原因。其他的,如有错误请指正。

【讨论】:

    【解决方案2】:

    试试这个

     $('#new-item-button').keydown(function (event) {
        if (event.keyCode == 13) {
               $('#new-item-button').trigger('click');
        }
      });
    

    【讨论】:

      猜你喜欢
      • 2017-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-10
      • 1970-01-01
      相关资源
      最近更新 更多