Javascript 输入触发器按钮单击

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4763638/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 13:58:26  来源:igfitidea点击:

Enter triggers button click

javascriptjqueryhtmlformsenter

提问by Rob Wilkerson

I have a page with two buttons. One is a <button>element and the other is a <input type="submit">. The buttons appear on the page in that order. If I'm in a text field anywhere in the form and press <Enter>, the button element's clickevent is triggered. I assume that's because the button element sits first.

我有一个带有两个按钮的页面。一个是<button>元素,另一个是<input type="submit">。按钮按该顺序出现在页面上。如果我在表单中任意位置的文本字段中并按下<Enter>click则触发按钮元素的事件。我认为那是因为按钮元素排在第一位。

I can't find anything that looks like a reliable way of setting the default button, nor do I necessarily want to at this point. In the absence of anything better, I've captured a keypress anywhere on the form and, if it was the <Enter>key that was pressed, I'm just negating it:

我找不到任何看起来像设置默认按钮的可靠方法的东西,此时我也不一定想要。在没有更好的情况下,我在表单的任何位置捕获了一个按键,如果<Enter>是按下的键,我只是否定它:

$('form').keypress( function( e ) {
  var code = e.keyCode || e.which;

  if( code === 13 ) {
    e.preventDefault();
    return false; 
  }
})

As far as I can tell so far, it seems to be working, but it feels incredibly ham-fisted.

到目前为止,据我所知,它似乎有效,但感觉非常笨拙。

Does anyone know of a more sophisticated technique for doing this?

有谁知道这样做的更复杂的技术?

Similarly, are there any pitfalls to this solution that I'm just not aware of?

同样,这个解决方案有什么我不知道的陷阱吗?

Thanks.

谢谢。

回答by Maddog

Using

使用

<button type="button">Whatever</button>

should do the trick.

应该做的伎俩。

The reason is because a button inside a form has its type implicitly set to submit. As zzzzBoz says, the Spec says that the first buttonor inputwith type="submit"is what is triggered in this situation. If you specifically set type="button", then it's removed from consideration by the browser.

原因是因为表单内的按钮将其类型隐式设置为submit。正如 zzzzBoz 所说,规范说 firstbuttoninputwithtype="submit"是在这种情况下触发的。如果您专门设置了type="button",则浏览器将不考虑它。

回答by zzzzBov

It is important to read the HTML specifications to truly understand what behavior is to be expected:

阅读 HTML 规范以真正了解预期的行为非常重要:

The HTML5 spec explicitly states what happens in implicit submissions:

HTML5规范明确规定在发生的事情implicit submissions

A form element's default button is the first submit button in tree order whose form owner is that form element.

If the user agent supports letting the user submit a form implicitly (for example, on some platforms hitting the "enter" key while a text field is focused implicitly submits the form), then doing so for a form whose default button has a defined activation behavior must cause the user agent to run synthetic click activation steps on that default button.

表单元素的默认按钮是树形顺序中的第一个提交按钮,其表单所有者是该表单元素。

如果用户代理支持让用户隐式提交表单(例如,在某些平台上,在文本字段聚焦时点击“输入”键隐式提交表单),则为默认按钮具有定义激活的表单执行此操作行为必须导致用户代理在该默认按钮上运行合成点击激活步骤。

This was not made explicit in the HTML4 spec, however browsers have already been implementing what is described in the HTML5 spec (which is why it's included explicitly).

这在 HTML4 规范中没有明确说明,但是浏览器已经实现了 HTML5 规范中描述的内容(这就是它被明确包含的原因)。

Edit to add:

编辑添加:

The simplest answer I can think of is to put your submit button as the first [type="submit"]item in the form, add padding to the bottom of the form with css, and absolutely position the submit button at the bottom where you'd like it.

我能想到的最简单的答案是将您的提交按钮作为[type="submit"]表单中的第一项,使用 css 在表单底部添加填充,并将提交按钮绝对放置在您想要的底部。

回答by Leinster

I don't think you need javascript or CSS to fix this.

我认为您不需要 javascript 或 CSS 来解决这个问题。

According to the html 5 spec for buttonsa button with no type attribute is treated the same as a button with its type set to "submit", i.e. as a button for submitting its containing form. Setting the button's type to "button" should prevent the behaviour you're seeing.

根据按钮html 5 规范,没有 type 属性的按钮被视为与类型设置为“提交”的按钮相同,即作为提交其包含表单的按钮。将按钮的类型设置为“按钮”应该可以防止您看到的行为。

I'm not sure about browser support for this, but the same behaviour was specified in the html 4.01 spec for buttonsso I expect it's pretty good.

我不确定浏览器对此的支持,但在html 4.01 规范中为按钮指定了相同的行为,所以我希望它非常好。

回答by Feniks502

By pressing 'Enter' on focused <input type="text">you trigger 'click' event on the first positioned element: <button>or <input type="submit">. If you press 'Enter' in <textarea>, you just make a new text line.

通过在焦点上按“Enter”,<input type="text">您会在第一个定位的元素上触发“click”事件:<button><input type="submit">。如果在 中按“Enter” <textarea>,则只需创建一个新文本行。

See the example here.

请参阅此处的示例。

Your code prevents to make a new text line in <textarea>, so you have to catch key press only for <input type="text">.

您的代码阻止在 中创建新的文本行<textarea>,因此您必须仅捕获<input type="text">.

But why do you need to press Enterin text field? If you want to submit form by pressing 'Enter', but the <button>must stay the first in the layout, just play with the markup: put the <input type="submit">code before the <button>and use CSS to save the layout you need.

但是为什么你需要Enter在文本字段中按下?如果您想通过按“Enter”提交表单,但<button>必须保留在布局中的第一个,只需使用标记:将<input type="submit">代码放在之前<button>并使用 CSS 来保存您需要的布局。

Catching 'Enter' and saving markup:

捕获“输入”并保存标记:

$('input[type="text"]').keypress(function (e) {
    var code = e.keyCode || e.which;
    if (code === 13)
    e.preventDefault();
    $("form").submit(); /*add this, if you want to submit form by pressing `Enter`*/
});

回答by Ram Thota

Where ever you use a <button>element by default it considers that button type="submit"so if you define the button type="button"then it won't consider that <button>as submit button.

<button>默认情况下,无论您在哪里使用元素,它都会考虑该按钮,type="submit"因此如果您定义该按钮,type="button"则它不会将其<button>视为提交按钮。

回答by Mehmet Ali Ku?

Dom example

DOM 示例

  <button onclick="anotherFoo()"> Add new row</button>
  <input type="text" name="xxx" onclick="foo(event)">

javascript

javascript

function foo(event){
   if(event.which == 13 || event.keyCode == 13) // for crossbrowser
   {
     event.preventDefault(); // this code prevents other buttons triggers use this
     // do stuff
   }
}

function anotherFoo(){
  // stuffs.
}

if you don't use preventDefault(), other buttons will triggered.

如果您不使用 preventDefault(),则会触发其他按钮。

回答by Sparafusile

Pressing enter in a form's text field will, by default, submit the form. If you don't want it to work that way you have to capture the enter key press and consume it like you've done. There is no way around this. It will work this way even if there is no button present in the form.

默认情况下,在表单的文本字段中按 Enter 将提交表单。如果您不希望它以这种方式工作,您必须捕获回车键并像您一样使用它。没有办法解决这个问题。即使表单中没有按钮,它也会以这种方式工作。

回答by Dave

You can use javascript to block form submission until the appropriate time. A very crude example:

您可以使用 javascript 阻止表单提交,直到适当的时间。一个非常粗略的例子:

<form onsubmit='return false;' id='frmNoEnterSubmit' action="index.html">

    <input type='text' name='txtTest' />

    <input type='button' value='Submit' 
        onclick='document.forms["frmNoEnterSubmit"].onsubmit=""; document.forms["frmNoEnterSubmit"].submit();' />

</form>

Pressing enter will still trigger the form to submit, but the javascript will keep it from actually submitting, until you actually press the button.

按 Enter 键仍会触发表单提交,但 javascript 会阻止它实际提交,直到您实际按下按钮。

回答by Satyajit

I would do it like the following: In the handler for the onclick event of the button (not submit) check the event object's keycode. If it is "enter" I would return false.

我会这样做:在按钮(不提交)的 onclick 事件的处理程序中,检查事件对象的键码。如果是“输入”,我会返回false。

回答by Dan Vachon

My situation has two Submitbuttons within the form element: Updateand Delete. The Deletebutton deletes an image and the Updatebutton updates the database with the text fields in the form.

我的情况Submit在表单元素中有两个按钮:UpdateDelete。该Delete按钮删除一个图像,该Update按钮使用表单中的文本字段更新数据库。

Because the Deletebutton was first in the form, it was the default button on Enterkey. Not what I wanted. The user would expect to be able to hit Enterafter changing some text fields.

因为Delete按钮是表单中的第一个,所以它是键上的默认按钮Enter。不是我想要的。用户希望Enter在更改某些文本字段后能够点击。

I found my answer to setting the default button here:

我在这里找到了设置默认按钮的答案:

<form action="/action_page.php" method="get" id="form1">
  First name: <input type="text" name="fname"><br>
  Last name: <input type="text" name="lname"><br>
</form>
<button type="submit" form="form1" value="Submit">Submit</button>

Without using any script, I defined the form that each button belongs to using the <button> form="bla"attribute. I set the Deletebutton to a form that doesn't exist and set the Updatebutton I wanted to trigger on the Enterkey to the form that the user would be in when entering text.

没有使用任何脚本,我使用<button> form="bla"属性定义了每个按钮所属的表单。我将Delete按钮设置为不存在的表单,并将Update我想在Enter键上触发的按钮设置为用户在输入文本时所在的表单。

This is the only thing that has worked for me so far.

这是迄今为止唯一对我有用的方法。