【问题标题】:Javascript scope with asp.net带有 asp.net 的 Javascript 范围
【发布时间】:2009-07-02 09:19:06
【问题描述】:

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

为了演示这个问题,我有以下示例 .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

【问题讨论】:

  • 做一个查看源代码,你会看到的。
  • 正如大家所说,这只是关于执行顺序,但退后一步,我想不出一个正当理由来做你试图用 Repsonse.Write 做的事情
  • 查看源代码确实显示了代码,但也许当我点击时,它正在编写一个新页面。我的问题源于我试图从该页面中的子表单调用加载到常规页面中的函数。我收集了 parent.helloWorld();就足够了,但我无处可去。干杯。

标签: javascript asp.net vb.net scope


【解决方案1】:

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

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

(并使用验证器 - 你不能在头部或身体之外有 &lt;script&gt; 标签。)

【讨论】:

    【解决方案2】:

    我认为 Response.Write 可能会擦除 PostBack 中的 helloWorld() 定义。尝试使用 PlaceHolder 将脚本标签插入 HTML。 丰富

    【讨论】:

    • 我明白你的意思,当我点击按钮时,它会呈现一个新页面。干杯。
    【解决方案3】:

    服务器端点击事件在任何内容呈现之前运行。因此 Response.Write 在响应中写入 html 元素之前就生成了脚本元素。在浏览器中使用 View Source 查看已写入的内容。

    尝试在帮助文档或 MSDN 中搜索“ASP.NET 页面生命周期”以了解此处发生的情况。

    【讨论】:

      猜你喜欢
      • 2013-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-18
      • 2011-03-01
      • 2015-01-22
      • 2019-05-01
      • 1970-01-01
      相关资源
      最近更新 更多