为修改输入的用户设置事件侦听器并设置对正确按钮的引用。然后有一个输入按钮的侦听器以触发提交引用的按钮。你没有提到 jQuery 或任何 JS 框架,所以我会尝试为普通的 javascript 编写它,我建议使用框架来支持跨浏览器。
var myButtonId = null;
var storeInputButtonId = function(buttonId) {
return function(event) {
myButtonId = buttonId;
};
};
//Do following for inputs, or your preferred event binding pattern
var fld = document.getElementById('myInputId');
//Statically refer to button id or replace with suitable algorithm
var inputButtonId = "";
if (fld.addEventListener) {
//Could bind to other events with logic based on input element type
fld.addEventListener('keyup',storeInputButtonId(inputButtonId), false);
}
//Method to trigger the button click event
function submitData(event){
//Watch for the enter button
if ( event.which == 13 ){
document.getElementById(myButtonId).click();
}
}
//Bind the listener to the enter button
var bodyElement = document.getElementsByTagName('body')[0];
if (bodyElement.addEventListener) {
bodyElement.addEventListener('keydown',submitData, false);
}