我尝试通过在 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/