1

I have created functions to create a Yes/No confirm window that popups with jQuery that I use in a .net project to confirm responses from the user. I have generated buttons that trigger functions depending on what you click on.

//load a specailized popup for confirming things in a localized manner function popupConfirm(TitleKey, InstructionsKey, YesFunction, NoFunction) {

//create the service to give us the content
var agpc = new AjaxServices.AjaxPopUps();

//get the results and open the popup with the functions aligned
agpc.GetLocalizedStrings(new Array(TitleKey, InstructionsKey, "Yes", "No"), function (results) {
    var content = jQuery.parseJSON(results.toString());

    //get the buttons for confirm/or not
    var YesNoButtons = jQuery('<div></div>', { id: 'YesNoButtons' });
    var yesButton = jQuery('<a>' + content.Yes + '</a>');
    var noButton = jQuery('<a>' + content.No + '</a>');

    //add the event handlers
    yesButton.click(YesFunction);
    noButton.click(NoFunction);

    //set a nice pointer for mouse over
    yesButton.css({ cursor: 'pointer' });
    noButton.css({ cursor: 'pointer' });

    YesNoButtons.append(yesButton).append(noButton);
    //show the box
    openPopup("Non-JSON", YesNoButtons, eval('content.' + TitleKey), eval('content.' + InstructionsKey));

    });
}

Well now comes the difficult part. The company also wants keypresses to trigger the yes/no functions. An enter key should trigger yes and escape should trigger no. I have no real idea how I will do this with this type of setup.

You can ignore most of the code in there. It is to get localized strings from the server. It the adding the keydown() event that I can't figure out.

Any ideas?

4

1 回答 1

1

好吧,这不是很难做到,只需尝试自定义调整并使用以下跨浏览器支持的代码。

如果您需要捕捉事件键(键盘上按下的键)并执行一些操作:

$("#YourDialog").keypress( function(event) {  // when you do a key press inside of the element with ID YourDialog 
    var keyCode = event.keyCode ? event.keyCode : event.which;
    if( event.keyCode == 13 || event.keyCode == 27 ) { // catching event for clicking either enter key or escape key.
     $("#OkButton").trigger('click');
     // or $("#YourDialog").hide(); to hide your dialog.
    }
});

相反,如果您需要阻止默认键操作,则必须使用此代码:

$("#YourDialog").keypress( function(event) {  // when you do a key press inside of the element with ID YourDialog 
    var keyCode = event.keyCode ? event.keyCode : event.which;
    if( event.keyCode == 13 || event.keyCode == 27 ) { // catching event for clicking either enter key or escape key.
     event.preventDefault();  // preventing the default action - so, in this case, when the enter or escape is pressed nothing will happen. Especially it's important when you want to prevent user from click some keys. 
     event.stopPropagation();
    }
});

您必须捕获用户事件(按下的键)。键码 13 是指回车键,键码 27 是指退出键。keyCode 变量普遍适用于所有浏览器,包括 Internet Explorer。

另请参阅此处以获取完整的keyCode 列表

我希望这对你有用。

于 2012-08-22T18:06:32.927 回答