繁体   English   中英

使用 JavaScript 按回车键触发预定义事件

[英]use JavaScript to press enter key to trigger pre-defined events

我需要使用 JavaScript 更新输入字段中的一些数据,然后以编程方式模拟“Enter”按键,以便触发该字段的某些事件以验证数据。

请注意,我没有开发该网站。 我只是为一些定制做一些附加脚本。 因此,我不知道该字段附加了哪些确切的事件,或者将被解雇。 我所知道的是,如果我手动执行此操作,在输入 item# 并按 Enter 后,它将执行一些验证操作。

我之前在这里搜索过结果。 我尝试了以下 3 种方法,但都失败了。

关于如何解决的更多想法?

#1:

const kexx = new KeyboardEvent('keypress', {
    bubbles: true, cancelable: true, keyCode: 13
});
    
inputEle.dispatchEvent(kexx);

#2:

    var exx = jQuery.Event("keypress");
    exx.which = 13; //choose the one you want
    exx.keyCode = 13;

$(inputEle).trigger(exx);

#3:

$(inputEle).val(itemnbrInputAry[i]).trigger('keyup');

如果某些内容无效,“提交”事件将触发验证。 “提交”事件只能在不源自任何其他元素的<form>上触发。 有关“提交”事件的所有详细信息都在下面的示例中。

 const io = document.forms.ui.elements; const triggerSubmit = e => e.target.form.submit(); io.B1.onclick = triggerSubmit;
 :root { font: 1ch/1.5 'Segoe UI' } body { font-size: 2ch } form { font-size: 1.5rem } [type='text'], button, label { display: block; font: inherit; margin: 3px 5px } button { display: inline-block; } [type='text'] { width: 90%; } code { font-family: Consolas; font-weight: 900; color: green } kbd { font-weight: 900; color: #930 } legend { font-size: 2rem } section { width: 90%; margin: 3px auto; font-size: 1.5rem } p { margin-top: 0 }
 <form id='ui'> <fieldset> <legend>Submit Event</legend> <label>Once the inputs are valid, and focus is on either one of them, hitting the <kbd>Enter/Return</kbd> key triggers a "submit" event on the <code>form</code></label> <input name='A' type='text' placeholder='This does not have the [required] attribute'> <input name='B' type='text' placeholder='This has the [required] attribute' required> <label>Both buttons are functionally identical. They both trigger a "submit" event on the <code>form</code></label> <button>Submit</button> <input type='submit' value='Submit'> </fieldset> </form> <section> <button name='B1' form='ui' type='button'>#1</button> <button name='B2' form='ui' type='button'>#2</button> <button name='B3' form='ui'>#3</button> <p>Button <kbd>#1</kbd>, <kbd>#2</kbd>, and <kbd>#3</kbd> are associated to <code>form</code> by the <code>[form]</code> attribute. <kbd>#2</kbd> is inert but <kbd>#1</kbd> has an event handler bound to it called <code>triggerSubmit(e)</code> which executes an <i>"synthetic"</i> "submit" event using <code>.submit()</code> method. This synthetic submit event bypasses validation. Neither <kbd>#1</kbd> or <kbd>#2</kbd> could invoke a "submit" event normally because they have <code>[type="button"]</code> attribute. <kbd>#3</kbd> does not have any <code>[type]</code> attribute and is associated to <code>form</code> so it will trigger a "submit" event.</p> </section>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM