jQuery AJAX 通过热键提交

标签 jquery ajax hotkeys

我正在尝试设置“Ctrl+Enter”来执行函数update:

document.onkeydown = function(e, id){
    var keyCode = (window.event) ? e.which : e.keyCode;
    if (keyCode == 13 && e.ctrlKey) {
        update(id);
    }
}
function update(id) {
    var title = $("#title"+id).val();
    var content = $("#content"+id).val();
        $.ajax({
            type: "POST",
            url: url,
            data: {
                aid: id,
                title: title,
                content: content,
            },
            beforeSend : function(){
                alert(content);
            },
            success: function(data){
                $("#view"+id).html(data);
            },

        });  
}

HTML 部分:

<input type="text" id="title<?php echo $id ?>" >
<textarea id="content<?php echo $id ?>" ></textarea>

它适用于单击事件,但适用于按键。我用上面的 beforeSend 进行了测试,它返回了 undefined。是什么导致变量 content 变为 undefined?我该如何解决它?

最佳答案

我为您制作了一个小型的工作示例:

$(document).keydown(function(event)
  {
      var currKey=0,e=e||event; 
      currKey=e.keyCode||e.which||e.charCode;

      if (!( currKey == 13 && event.ctrlKey) && !(event.which == 19))
        {
            return true; 
        }    
      event.preventDefault();       
      alert("Ctrl + Enter was pressed"); // Replace this with your update(id);
      return false;
  }); 

关注以下示例中的输入字段,并尝试按Ctrl+Enter查看其实际效果。

Online Demo

编辑1:

使您的content变量未定义的原因是它的范围。您明确地说 var content 并将其范围设置为本地,同时尝试从另一个函数访问它。

var content替换为content,你就会得到你想要的!

说明:

JavaScript has two scopes: global and local. A variable that is declared outside a function definition is a global variable, and its value is accessible and modifiable throughout your program. A variable that is declared inside a function definition is local. It is created and destroyed every time the function is executed, and it cannot be accessed by any code outside the function. JavaScript does not support block scope (in which a set of braces {. . .} defines a new scope), except in the special case of block-scoped variables.

关于jQuery AJAX 通过热键提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22742961/

相关文章:

javascript - Zepto 中的绑定(bind)事件

visual-studio - 自动命名空间导入

jquery - 在 jquery 中传递 self 对象

php - Ajax 调用不传递任何 POST 值

javascript - 文件自动上传时如何禁用 Dropzone.js 中的提交表单

javascript - 如何在没有外部库的情况下在 React 中实现 Google Maps JS API?

javascript - MVC : Get JSON data from a controller using AJAX failed

java - JButton 的热键/快捷方式

javascript - 文本区域 Shift+Enter 进入下一行并 Enter 提交表单

javascript - 线路按钮动画