IE bug触发点击2个按钮? [英] IE bug triggers click for 2 buttons?
问题描述
我正在尝试在用户按Enter键时触发提交按钮。适用于除Internet Explorer 9之外的所有浏览器。奇怪的是,IE坚持也会触发我从未告诉过的另一个按钮的点击。我做错了什么或如何解决这个问题?
I am trying to trigger the submit button when a user presses enter. Works great for all browsers except Internet Explorer 9. Strange thing is that IE insists on also triggering the click for another button I never told it to. Am I doing something wrong or how to fix this?
以下是我的代码。在IE中按Enter键会按预期触发提交点击,但由于某种原因也会触发某个按钮点击(即使没有我的按键监听器):
Below is my code. Pressing enter in IE triggers the submit click as expected, but for some reason also triggers the "some button" click (even without my keypress listener):
$('input[type=submit]').click(function () {
alert('Submit click');
});
//SIMULATE CLICK IF ENTER PRESSED IN SEARCH
$('input[type=text]').keypress(function (event) {
var keycode = event.keyCode || event.which;
if (keycode == 13) $('input[type=submit]').click();
});
//ROUTE CLEAR HANDLER
$('button').click(function () {
alert('Button click');
});
您可以在此处看到错误:http://jsfiddle.net/h64xD/
You can see the bug in action here: http://jsfiddle.net/h64xD/
推荐答案
这里有几件事考虑:
IE9将< button />
元素计为 type =默认情况下提交
。因此,要使其不提交,您必须明确:
IE9 counts the <button/>
element as type="submit"
by default. So to make it non-submit, you have to be explicit:
<button type="button">Some button</button>
如果你这样做,你会注意到模拟的点击
事件现在不会触发< button />
但仍会触发2个事件。原因是,因为您没有明确定义< form />
元素,IE9会将控件视为表单形式,因此按下在文本框中输入
触发2个事件:
If you do that, you will notice that the emulated click
event now doesn't trigger the <button/>
but still fires 2 events. The reason is that, because you haven't explicitly defined a <form/>
element, IE9 assumes the controls as being in a form, and thus pressing enter
in the textbox triggers 2 events:
- 您正在模拟的那个
- 默认表单提交按钮行为
因此,要解决此问题,您必须明确:
So again to get around this issue, you have to be explicit:
<button type="button">Some button</button>
<form><input type="text" /></form>
<input type="submit" value="Submit" />
现在,这些是您在IE中看到行为的原因。 @MrSlayer 的答案迎合了第二期停止 keypress
使用 preventDefault()
Now, these are the reasons that you are seeing the behaviour in IE. @MrSlayer's answer caters to the second issue of stopping the keypress
event after you have satisfactorily handled it, using preventDefault()
这篇关于IE bug触发点击2个按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!