我目前正在用 JavaScript 编写自定义对话框脚本(以显示带有按钮、标题等选择的对话框),从而模仿 C# 的 MessageBox.Show() 方法。但是,我在从函数正确返回值时遇到问题。
例如,我创建的 Show() 方法是静态的,并通过单击按钮进行如下调用:
<input type="button" onclick="return MessageBox.Show(dialogueMessage, 'Really Delete?', 'confirm', false)") />
调用 MethodBox.Show() 函数后,将显示该对话框。我想要这个选项,以便当用户单击"is"按钮时,MessageBox.Show() 函数返回 true,否则返回 false。我用于创建(动态)按钮的代码如下:
var yesButton = document.createElement('input');
yesButton.setAttribute('type', 'button');
yesButton.setAttribute('value', 'Yes');
yesButton.setAttribute('name', 'button-yes');
yesButton.onclick = function() { MessageBox.Hide(); return true; };
var noButton = document.createElement('input');
noButton.setAttribute('type', 'button');
noButton.setAttribute('value', 'No');
noButton.setAttribute('name', 'button-no');
noButton.onclick = function() { MessageBox.Hide(); return false; };
但是,正如您所理解的,“return false”/“return true”语句指的是按钮本身,而不是函数 (MessageBox.Show())。我想知道的是,是否有一种方法可以在(且仅当)用户单击其中一个按钮时返回该函数,以便可以正确使用单击的调用该函数的按钮。
我很难解释我想要实现的目标,但以上内容应该是有道理的。
谢谢, 本。
最佳答案
您执行此操作的方式不会让您返回任何值,因为该函数在创建对话框后立即完成。 我假设您想取消按下按钮时的默认操作...所以请执行以下操作。
如果按钮在 Javascript 中位于 var theButton 中。
theButton.addEventListener('click',
function(e)
{
e.preventDefault(); // So clicking will not fire any submit
// if the button was inside a form element.
MessageBox.Show(dialogueMessage, 'Really Delete?', 'confirm', false, this);
// Here I send a button reference to be able to fire the event ______↑
// you must add an extra parameter to hold it then...
} 1);
然后在 MessageBox.Show() 方法中,执行以下操作,假设 this 关键字被传递为,buttonRef.-
var yesButton = document.createElement('input');
yesButton.setAttribute('type', 'button');
yesButton.setAttribute('value', 'Yes');
yesButton.setAttribute('name', 'button-yes');
yesButton.onclick = function() { MessageBox.Hide(); butonRef.click(); };
var noButton = document.createElement('input');
noButton.setAttribute('type', 'button');
noButton.setAttribute('value', 'No');
noButton.setAttribute('name', 'button-no');
noButton.onclick = function() { MessageBox.Hide(); };
然后,如果按下 yes,输入元素将触发提交事件,就像按下它一样。
关于JavaScript:从 onclick 函数内部返回所有者方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3046409/