按钮上的JavaScript功能单击

JavaScript Function on Button Click

本文关键字:功能 单击 JavaScript 按钮      更新时间:2023-09-26

嗨,我正在编写java脚本,我正在aspx页面上编写java脚本函数并调用该函数,该函数将在按钮单击事件上返回值,但是当我单击按钮时,该函数没有被调用这是我的代码。

Java Script Function

function CheckAge(age)
{
if (age > 18)
return true;
else
return false;                
}

这里是按钮点击事件在CSfile

try
{
bool check = false;
try
{
btnAge.Attributes.Add("onClick", "javascript:return CheckAge('" + txtAge.Text + "')");
if (check)
Response.Write("You Are Eligible");
else
Response.Write("You Are Not Eligible");
}
catch (Exception err)
{
Response.Write(err.Message);
}
}
catch (Exception)
{
throw;
} 
}

请帮帮我,能不能给一下代码

未设置变量check。试试这个:

  btnAge.Attributes.Add("onClick", "javascript:var check=CheckAge('" + txtAge.Text + "')");

问题是.aspx代码是在页面发送给用户之前计算的。这些代码将在用户接收到页面之前立即运行。一旦用户有了页面,任何javascript都不能运行aspx,除非它刷新页面或调用另一个。

要么用Javascript编写整个函数,要么用aspx可以处理的GET变量重载页面。

JS:

function CheckAge(age)
{
    if (age > 18) document.location.href = "index.aspx?allowed=1";
    else document.location.href = "index.aspx?allowed=0";                
}
ASP:

try
{
    if(Request.QueryString["allowed"]==1) Response.Write("You Are Eligible");
    if(Request.QueryString["allowed"]==0) Response.Write("You Are Not Eligible");
}
catch (Exception)
{
    throw;
}