我正在尝试设置“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
查看其实际效果。
编辑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/