You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JsPsych中配置button_html并支持'r'键重复试次

解决JsPsych中隐藏重复按键并实现试次重复的问题

问题核心

你原来的代码把'r'放到了choices数组里,导致button_html会生成一个src为'r'的无效图片按钮,完全不符合“仅支持按键触发、不显示按钮”的需求。正确的做法是把按键监听和按钮响应分开处理,不要将键盘键作为按钮选项。

修改后的完整代码

// 定义变量标记是否需要重复试次
let repeat_trial = false;
let keyboard_listener = null;

var sound_trial = {
  type: jsPsychAudioButtonResponse,
  stimulus: 'sound/Centrifuge.mp3',
  // 移除choices中的'r',只保留图片选项
  choices: ['img/test1.png', 'img/test2.png', 'img/test3.png', 'img/test4.png'],
  prompt: "<p>Hvilket billede passer til ordet?</p>",
  button_html: '<img src="%choice%" /></button>',
  name: 'soundtrial',
  on_load: function() {
    // 注册'r'键的监听事件
    keyboard_listener = jsPsych.pluginAPI.getKeyboardResponse({
      callback_function: function() {
        // 按下'r'时标记需要重复试次
        repeat_trial = true;
        // 结束当前试次,触发loop判断
        jsPsych.finishTrial();
      },
      valid_responses: ['r'],
      rt_method: 'performance',
      persist: false,
      allow_held_key: false
    });
  },
  on_finish: function (data) {
    jsPsych.data.addProperties({ sound: data.response });
    // 移除键盘监听,避免影响后续试次
    if(keyboard_listener) {
      jsPsych.pluginAPI.cancelKeyboardResponse(keyboard_listener);
    }
  }
};

var loop_node = {
  timeline: [sound_trial],
  loop_function: function(data){
    // 检查是否需要重复试次
    const should_repeat = repeat_trial;
    // 重置标记,避免无限循环
    repeat_trial = false;
    return should_repeat;
  }
};

timeline.push(loop_node);

关键修改说明

  • 移除choices中的'r':彻底避免生成无效的重复按钮,保证界面只有图片选项。
  • 单独监听'r'键:用jsPsych.pluginAPI.getKeyboardResponse在试次加载后注册监听,按下'r'时直接结束当前试次并标记重复需求。
  • 自动清除监听:在on_finish中移除键盘监听,防止后续试次受到干扰。
  • 重置重复标记:每次loop判断后重置标记,确保只有按下'r'时才会重复试次,不会无限循环。

内容的提问来源于stack exchange,提问作者carolinehommel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 18:01:23