asp.net - 为什么我需要 RegisterStartupScript 来实现 asp.net 中的简单 jquery helloworld?

标签 asp.net jquery

我尝试通过在 webform 中包含 javascript 来调用我的 helloworld,但是在 chrome 和 firefox 上运行它时,页面都是空白的。在 Firefox 中错误是

"XML Parsing Error: no element found"

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="jquery01._Default" %>

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

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"> 
        </script>
<script type="text/javascript">
    function helloWorld() {
        $("#divSample").append("Hello World!!");
    }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div id="divSample">

    </div>
<script type="text/javascript">    helloWorld();</script>
    </form>
</body>
</html>

我需要添加代码隐藏:

protected override void  Render(HtmlTextWriter writer)
{

    this.Page.ClientScript.RegisterStartupScript(this.Page.GetType(),
        "startup", "<script type=\"text/javascript\">helloWorld();</script>");
    base.Render(writer);
}

在这种情况下它可以工作,但我不明白为什么我不能使用第一种语法,为什么对于如此简单的东西来说它如此复杂?

我也尝试了该建议,但也不起作用:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="jquery01._Default" %>

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

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"> 
        </script>
<script type="text/javascript">
    function helloWorld() {
        $("#divSample").append("Hello World!!");
    }
    </script>
<script type="text/javascript">
    $(document).ready(function () {
        helloWorld();
    });
</script>

</head>
<body>
    <form id="form1" runat="server">
    <div id="divSample">

    </div>
    </form>
</body>
</html>

更新:似乎 ASP.NET 在某些情况下使用 ajax/jquery 可能不可靠? http://chiragrdarji.wordpress.com/2010/02/17/xml-parsing-error-no-element-found/

最佳答案

尝试用 jQuery $(document).ready 语法包装 helloWorld() 调用:

<script type="text/javascript">
    $(document).ready(function(){
        helloWorld();
    });
</script>

关于asp.net - 为什么我需要 RegisterStartupScript 来实现 asp.net 中的简单 jquery helloworld?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3866511/

相关文章:

c# - ASP.NET 和 EF 非常非常慢

javascript - 使用 jQuery 匹配动态添加的事件(作为属性)

javascript - 排序 json 列表?

javascript - 代笔 - 需要更大的 Canvas

javascript - 为什么这个 Js/jquery 代码使用 %70 的 CPU?

具有流体/液体宽度的 jQuery 图像轮播

asp.net - 此站点无法提供安全连接 (ERR_SSL_PROTOCOL_ERROR)

html - 与用新类覆盖现有 CSS 类相关的问题

html - 在母版页中定义的表单上应用样式

javascript - jquery hover() 不触发