ON:keydown事件,带有sevelte中的Enter键

发布于 2025-01-24 20:48:34 字数 394 浏览 3 评论 0原文

我正在使用on Smvelte:单击按钮上的事件。单击此按钮时,我将一些信息派遣到更高的组件。我想做的是点击Enter键,但是on:keydown似乎不起作用?击中Enter时,该如何将其开火?

<button on:click={() => 
   dispatch('search', { searchword: item })}
>ClickMe</button>
<button on:keydown={() => 
   dispatch('search', { searchword: item })}
>PressEnter</button>

I am using svelte with an on:click event on a button. When this button is clicked, I dispatch some information to a higher component. What I would like to do is hit the enter key instead, but on:keydown doesn't seem to work? How can I get this to fire when hitting enter?

<button on:click={() => 
   dispatch('search', { searchword: item })}
>ClickMe</button>
<button on:keydown={() => 
   dispatch('search', { searchword: item })}
>PressEnter</button>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

杀お生予夺 2025-01-31 20:48:34

Enter将自动触发单击如果按钮具有焦点或是表单的一部分,并且被隐式单击作为表单提交的一部分。

通常,我建议使用表格,然后在&lt; Input&gt;中输入会导致表单提交。然后,也可以直接处理表格的提交事件,因为无论如何都可能需要取消,除非需要重新加载页面。

示例:

<script>
    let value = '';
    let submittedValue = null;
</script>

<form on:submit|preventDefault={() => submittedValue = value}>
    <label>
        Search
        <input bind:value />
    </label>
    
    <button on:click={() => console.log('button clicked')}>GO</button>
</form>

{#if submittedValue != null}
    <p>Submitted: {submittedValue}</p>
{/if}

repl

Enter will automatically fire click if the button has focus or is part of a form and is clicked implicitly as part of the form submission.

Generally I would recommend using a form, then Enter within an <input> will cause a form submission. One can then also directly work with the form's submit event, as that may need cancelling anyway, unless the page reload is desired.

Example:

<script>
    let value = '';
    let submittedValue = null;
</script>

<form on:submit|preventDefault={() => submittedValue = value}>
    <label>
        Search
        <input bind:value />
    </label>
    
    <button on:click={() => console.log('button clicked')}>GO</button>
</form>

{#if submittedValue != null}
    <p>Submitted: {submittedValue}</p>
{/if}

REPL

并安 2025-01-31 20:48:34

这个问题是一台州机器提供重点/不给予重点。该项目正在使用Xstate来管理很多。

The issue was a state machine giving focus/ not giving focus. This project was using xstate to manage alot.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文