问题描述
我正在尝试使用 jQuery 自动触发向下箭头 keyup 事件。 annotorIoUs/seadragon 组合有一个监听器,当我按下向下箭头时,它会打开所有预配置的标签。
我已经编写了 jQuery 代码来查找输入字段,将焦点放在它上面然后触发 keyup 事件。
function triggerDownArrowOninput() {
$("[id^=downshift][id$=input]").each(function(index) {
// There should only be 1,but let's not assume.
console.log(index);
if (index == 0) {
console.log("Found an input: " + $(this).attr("id"))
$(this).focus();
var event = jQuery.Event("keyup");
event.keyCode = event.which = 40; // down arrow
$(this).trigger(event);
} else {
console.log("Multiple elements found that match the id: " + $(this).attr("id"));
} // if
})
} // triggerDownArrowOnInput
焦点效果很好,但不是触发器。如果我手动按下向下箭头键,那么预配置的标签都会出现:
我分别试过“keyCode”和“which”。
我尝试触发 $(this).keyup(event)。
我试过调用 $(document).trigger(event)。
我以为我可能将事件发送到错误的元素,但似乎(通过开发工具)只有输入字段和文档启用了侦听器。
无论我做什么,都无法触发事件。有什么想法吗?
谢谢。
解决方法
我想我可以在没有 jQuery 的情况下使用 KeyboardEvent
和 dispatchEvent
完成这项工作。通过我的测试,我认为您也不需要事先关注焦点,因为它是元素上的事件,但值得在您的应用程序上进行测试。
function triggerDownArrowOnInput() {
$("[id^=downshift][id$=input]").each(function(index) {
// There should only be 1,but let's not assume.
console.log(index);
if (index == 0) {
console.log("Found an input: " + $(this).attr("id"))
$(this).focus();
this.dispatchEvent(new KeyboardEvent('keyup',{'keyCode': 40,'key':'ArrowDown','code':'ArrowDown'}));
} else {
console.log("Multiple elements found that match the id: " + $(this).attr("id"));
}
})
}
,
你试过keydown
吗?
var e = jQuery.Event("keydown");
e.which = 40;
e.keyCode = 40
$(this).trigger(e);
function triggerDownArrowOnInput() {
$("[id^=downshift][id$=input]").each(function(index) {
// There should only be 1,but let's not assume.
console.log(index);
if (index == 0) {
console.log("Found an input: " + $(this).attr("id"))
$(this).focus();
var event = jQuery.Event("keydown");
event.keyCode = event.which = 40;
$(this).trigger(event);
} else {
console.log("Multiple elements found that match the id: " + $(this).attr("id"));
}
})
} // triggerDownArrowOnInput
我能够触发事件,但仍然无法在焦点上打开菜单。我最终不得不为以下项目创建一个开发环境:
recogito/recogito-client-core
recogito/recogito-js
recogito/annotorious
recogito/annotorious-openseadragon
然后我修改了 recogito/recogito-client-core 中的 Autocomplete.jsx,添加了一个 OnFocus 监听器,然后添加了以下代码:
const onFocus = evt => {
if (!isOpen) {
this.setState({ inputItems: this.props.vocabulary }); // Show all options on focus
openMenu()
} // if
} // onFocus
比我想做的要多得多,但它现在正在发挥作用。