好的,我想出了一个解决方法。我将首先做一个简短的解释,然后为将来可能会看到此页面的人做一个更长的解释,因为像我这样可能不知道这些东西的爱好者可以使用它来获得一些帮助。(因为我靠谷歌搜索这些东西为生。)
我正在寻求的功能是根据单击的按钮有一个具有不同 innerHTML 的模态 div。如果页面有效,我也只希望 div 显示,而不是页面上的所有按钮都会导致验证。
练习是创建一个全局变量“ButtonClicked”。然后,页面上的每个按钮都必须将 javascript 分配给它的 onclick 属性,该属性将 ButtonClicked 变量设置为按钮的 id。分配给 onclick 的脚本在页面验证之前运行。然后,使用 ClientScript.RegisterOnSubmitStatement,我分配了一个函数,以便在页面成功验证后、实际提交页面之前调用。然后我可以访问“ButtonClicked”事件以查看刚刚调用了哪个按钮,然后更改模态 div 的 innerHTML,然后显示它。(然后做一个 asyc 回发,然后在回发后删除模态 div。)
为什么我不能从按钮调用自己的函数中设置模态 div 的 innerHTML?因为我放在那里的 innerHTML 取决于页面是否有效,而我只有在获得 ShowSplashScreen 函数时才知道页面是否有效。您可能还会问为什么我不只是从按钮调用的 javascript 函数中调用要验证的页面。这是因为这样做会导致验证被调用两次,并且页面上的信息太多以至于验证页面需要将近一秒钟的时间,并且因为客户端验证函数本身有一些东西只能被调用一次在验证期间。
所以这一切的最终结果是,在验证之前单击时,函数1和函数2都由它们各自的按钮调用,而ShowSplashScreen在验证之后由任一按钮调用(仅当页面有效时),然后我访问全局变量看看哪个被点击了。
所以整个事情看起来像这样:
HTML
<!-- This is a simplified version of the HTML that <asp:Button> is going to
output in the actual HTML -->
<input type="submit" id="Button1" value="Load Page" onclick="function1(this)">
<input type="submit" id="Button2" value="Save Page" onclick="function2(this)">
JavaScript
var ButtonClicked = ""; //Needs to be global
//It is not necessary to have a different function for each button,
//I just needed to for the needs of my page. If Button2 calls function1
//instead of function2, ButtonClicked is still set to "Button2".
//It is very important that EVERY button on the page calls something
//that sets ButtonClicked or you will get an bug if the user ever
//clicks a button that sets ButtonClicked, and then clicks a button
//that does not set ButtonClicked (the final function will still
//think that the first button had just been clicked)
function function1(source){
ButtonClicked = source.id;
//whatever else Client Script that needs to be run from this button
}
function function2(source){
ButtonClicked = source.id;
//whatever else Clinet Script that needs to be run from this button
}
function ShowSplashScreen(){
if(ButtonClicked == "Button1")
//Use JQuery to access the dialog <div> and set the innerHTML
//to whatever
else if(ButtonClicked == "Button2")
//Use JQuery to access the dialog <div> and set the innerHTML
//to something else
}
服务器端
//Use this code to set a function to be called after the page has
//been successfully validated. If a button does not cause validation,
//then that button will always call the function set here
//
//You should also check to see if the script has already been registered
//for speed purposes, but I'm just demonstrating particular
//functionality here.
protected void Page_Load(object sender, EventArgs e)
{
ClientScript.RegisterOnSubmitStatement(this.GetType(), "ShowSplashScreen",
"ShowSplashScreen()");
}