如何使用 Enter 键提交表单而不使用提交按钮
我让 jQuery 遍历所有带有 button 类的提交按钮,并将它们每个都变成带有该类按钮的锚元素。
$("input.button").each(function(i) {
var anchorButton = $("<a class='"+this.className+"' href='#'>"+this.value+"</a>")
anchorButton.click(function(eventObject) {
$(this).blur().prev("input.hidden").click();
return false;
});
$(this)
.after(anchorButton)
.addClass("hidden")
.removeClass("button pill-left pill-center pill-right");
});
然后我可以使用 CSS 跨浏览器设置锚元素的样式。只有一个问题。每当我在表单输入元素上按 Enter 键时,表单都不会提交。但是,如果我取消隐藏提交按钮,它会再次起作用。总之,除非有可见的提交按钮(显示!=无),否则我无法使用 Enter/Return 键来提交表单。
当我隐藏提交按钮时,如何在按 Enter 时提交表单?
I have jQuery go though all the submit buttons with the class button, and turn them each into an anchor element with the class button.
$("input.button").each(function(i) {
var anchorButton = $("<a class='"+this.className+"' href='#'>"+this.value+"</a>")
anchorButton.click(function(eventObject) {
$(this).blur().prev("input.hidden").click();
return false;
});
$(this)
.after(anchorButton)
.addClass("hidden")
.removeClass("button pill-left pill-center pill-right");
});
I can then style the anchor element with CSS, cross-browser-ly. There's only one problem. Whenever I press the Enter key on form input elements, the form doesn't submit. However, if I un-hide the submit button, it works again. In conclusion, I can't get the Enter/Return key to submit the form unless I have a submit button visible (display != none).
How can I get the form to submit when I press Enter when I have the submit button hidden?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这应该有效。
如果不尝试这样做:
这比建议的
visibility:hidden
解决方案更好,因为如果您将可见性设置为隐藏,按钮仍然会“占用空间”。This should work.
If it doesn't try this:
This is better than the proposed
visibility: hidden
solutions since if you set the visibility to hidden the button will still "take up space".只需在 HTML 中使用普通的
form
即可,包括 Submitaction
属性。然后您将获得浏览器的默认行为,并在表单中按 Enter 将提交它。那么您就不必使用 jQuery 将事件处理程序绑定到所有提交按钮。您可以使用此 JSBin 进行测试。
Just use an ordinary
form
in your HTML, including a submitaction
attribute. Then you'll get the browser's default behaviour and pressing Enter within the form will submit it. Then you don't have to use jQuery to bind event handlers to all your submit buttons.You can test it with this JSBin.
您是否尝试过将可见性更改为隐藏而不是显示为无?
Have you tried changing the visibility to hidden instead of display to none?
尝试可见性=隐藏
Try visibility=hidden