Javascript 作用域与 asp.net

标签 javascript asp.net vb.net scope

我可能在这里错过了一些基本的东西,但这对我来说似乎相当棘手和令人困惑,所以这里是......

为了演示该问题,我有以下示例 .aspx 页面

<%@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
    Response.Write("<script type=text/javascript>alert('Alert from response.write')" & ";</sc" & "ript>")
End Sub

Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs)
    Response.Write("<script type=text/javascript> helloWorld(); </sc" & "ript>")
End Sub

Protected Sub Button3_Click(ByVal sender As Object, ByVal e As System.EventArgs)
    Response.Write("<script type=text/javascript> helloWorld(); </sc" & "ript>")
End Sub
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
<script type="text/javascript">
    function helloWorld() 
    {
        alert('hello!');
    }
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
    <asp:Button runat=server ID="Button1" text=1 OnClick="Button1_Click" />
    <asp:Button runat=server ID="Button2" text=2 OnClick="Button2_Click" />
    <asp:Button runat=server ID="Button3" text=3 OnClick="Button3_Click" OnClientClick="helloWorld();" />
    <asp:Button runat=server ID="Button4" text=4/>
</div>
</form>
</body>
</html>

所以,我有3个按钮,第一个调用response.write来执行JS警报..这有效。 第二个尝试调用 head 标记中定义的 helloWorld() 。这不起作用。 第三个在response.write 和 onClientClick() 中都调用了 helloWorld() - 只有 onClientClick 有效。

有人可以解释一下为什么我不能使用response.write方法调用helloWorld()吗?

干杯:D

最佳答案

您在包含该函数的 HTML 下载之前就调用了 helloWorld。

在调用函数之前定义它们。

(并使用验证器 - 在头部或正文之外不能有 <script> 标签。)

关于Javascript 作用域与 asp.net,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1073354/

相关文章:

javascript - Jquery 图像加载取消

c# - 指定的类型转换无效?

asp.net - 查询字符串中的斜杠问题

html - 不同的浏览器以不同的方式呈现相同的代码

c# - “字段”不是 'System.Data.DataRow' 的成员

javascript - 如何在 JavaScript 或 jQuery 中 1 秒后删除类?

javascript - 查找对象树是否具有给定属性

javascript - 需要了解一些正则表达式

c# - Entity Framework 代码优先 : how to add more props on model and update database?

c# - 无法访问已处置的对象