jquery - 在表单上点击vs点击输入会产生不同的结果 - 为什么?

时间:2013-11-19 07:48:46

标签: javascript jquery ajax forms post

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

<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键盘事件,然后以编程方式单击按钮。单击该按钮时,应发生ajax post事件。这是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请求的预期行为?

2 个答案:

答案 0 :(得分:0)

在您的代码中,很明显,当您按 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 键之间存在差异。我想这应该是原因。其他人,如果我错了,请纠正我。

答案 1 :(得分:0)

试试这个

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