weixin_33734785 2014-03-30 10:40 采纳率: 0%
浏览 16

jQuery AJAX通过热键提交

I'm trying to set "Ctrl+Enter" to execute function 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 part:

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

It works with click event, but keypress. I tested with the above beforeSend and it returned undefined. What makes variable content become undefined? How could I fix it?

  • 写回答

1条回答 默认 最新

  • weixin_33701251 2014-03-30 11:14
    关注

    I made a small, working example for you:

    $(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;
      }); 
    

    Focus on input field in the following example and try pressing Ctrl+Enter to see it in action.

    Online Demo

    EDIT 1:

    What made your content variable undefined is that its scope. You explicitly say var content and make its scope local, while trying to access it from another function.

    Replace var content with content and you will get what you want!

    Explanation:

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了