我有这个WebForm
Html
:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GetLink.aspx.cs" Inherits="GetLink" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="hidden" runat="server" id="hdnVal" value="55"/>
</div>
</form>
</body>
</html>
我想在此代码中添加一个JavaScript
函数并使用以下代码运行它:
protected void Page_Load(object sender, EventArgs e)
{
if (!ClientScript.IsStartupScriptRegistered("key1"))
{
ClientScript.RegisterStartupScript(GetType(), "key1", @"<script type=""text/javascript"">function callMyJSFunction() { document.getElementById(""hdnVal"").value='5'; }</script>");
}
ClientScript.RegisterStartupScript(this.GetType(), "key1", "<script>callMyJSFunction();</script>");
string resutOfExecuteJavaScript = hdnVal.Value;
}
当我运行它时,hdnVal
的值保持55
的值不变。知道是什么问题吗?
答案 0 :(得分:2)
在注册 callMyJSFunction 的JavaScript函数时,您在Page_Load事件中的代码应调用ClientScript.RegisterClientScriptBlock
,而在您的代码中,您将此函数注册为启动脚本。这是代码中唯一的错误。
因此,如果将服务器端代码更改为以下代码,则它将按照您的期望工作。
protected void Page_Load(object sender, EventArgs e)
{
if (!ClientScript.IsClientScriptBlockRegistered("key1"))
{
//register your javascript function
ClientScript.RegisterClientScriptBlock(GetType(), "key1", @"<script type=""text/javascript"">function callMyJSFunction() { document.getElementById(""hdnVal"").value='5'; }</script>");
}
ClientScript.RegisterStartupScript(this.GetType(), "key1", "<script>callMyJSFunction();</script>");
string resutOfExecuteJavaScript = hdnVal.Value;
}
答案 1 :(得分:0)
第一个问题是您要在Clientscript中创建函数,而您只需将其放入javascript中,然后执行调用部分。第二个问题是您的函数正在调用该hiddenfield进行查看的时间仅在文档中不可用意味着停止将代码加载到页面加载上,而使用按钮单击事件。第三个问题是,您在很多不必要的地方使用了多个反逗号。
这对我有用
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$('document').ready()
{
function callMyJSFunction()
{
debugger;
document.getElementById('hdnVal').value = '5';
alert(document.getElementById('hdnVal').value);
}
// - including fonts, images, etc.
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="hidden" runat="server" id="hdnVal" value="55"/>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
</div>
</form>
</body>
</html>
并在CS页面上
protected void Button1_Click(object sender, EventArgs e)
{
ClientScript.RegisterStartupScript(this.GetType(), "key1", "<script>callMyJSFunction()</script>",false);
string resutOfExecuteJavaScript = hdnVal.Value;
}