我正在尝试创建“正确”和“不正确”按钮,分别触发“c”和“i”按键。我正在使用一个 jspsych 插件,它只能接受按键响应。按钮正在显示,但每次我单击一个按钮(并且不触发按键)时,我的代码都会引发无法解释的错误。
var simulateCorrectKeyPress = function(character) {
jQuery.event.trigger({ type : 'keypress', which : character.charCodeAt(0)});
}
$(function() {
$('body').keypress(function(e) {
alert(e.which);
});
simulateCorrectKeyPress('c');
});
var simulateIncorrectKeyPress = function(character) {
jQuery.event.trigger({ type : 'keypress', which : character.charCodeAt(0)});
}
$(function() {
$('body').keypress(function(e) {
alert(e.which);
});
simulateIncorrectKeyPress('i');
});
var correct_button = "<div> <button type='button' onclick='simulateCorrectKeyPress('c')'> Correct </button> </div>";
var incorrect_button = "<div> <button type='button' onclick='simulateIncorrectKeyPress('i')'> Incorrect </button> </div>";
最佳答案
var correct_button = "<div> <button type='button' onclick='simulateCorrectKeyPress('c')'> Correct </button> </div>";
var incorrect_button = "<div> <button type='button' onclick='simulateIncorrectKeyPress('i')'> Incorrect </button> </div>";
onclick
属性中的单引号正在结束该属性,因此 onclick
属性的其余部分会进入 HTML 标记。
您仅监听 body
元素上的 keypress
事件。您需要在整个窗口
上监听按键
。
更改此:$('body').keypress(function(e) {
为此:$(window).keypress(function(e) {
您还出现了两次重复代码。
$('body').keypress(function(e) {
alert(e.which);
});
这段代码在您的脚本中重复两次。它将连续两次向 e.which
发出警报。
您有一个 simulateCorrectKeyPress()
函数以及一个 simulateIn CorrectKeyPress()
函数。最好为两种 keypress
场景提供一个函数,因为每个场景中的函数代码完全相同。
var simulateCorrectKeyPress = function(character) {
jQuery.event.trigger({ type : 'keypress', which : character.charCodeAt(0)});
}
var simulateIncorrectKeyPress = function(character) {
jQuery.event.trigger({ type : 'keypress', which : character.charCodeAt(0)});
}
// Seriously?
或者您可以保留两个函数,但让它们不带参数。
simulateIncorrectKeyPress('i'); simulateCorrectKeyPress('c'); // Seriously?
关于javascript - 单击按钮触发按键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31417766/