【发布时间】:2021-08-23 00:20:03
【问题描述】:
我正在尝试运行一个 JS 函数,该函数使用 JQuery 将信息附加到 ASP 页面的 HTML 中,但我无法让它工作。我已经对此进行了一些研究,但也许它要简单得多。
%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="Pruebas.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript">
const add = (param) => {
alert("hi");
$("div.auto-style1").append("<p>'" + param + "'</p>");
}
</script>
<form id="form1" runat="server">
<div>
</div>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" style="height: 26px" Text="Button" />
<asp:DropDownList ID="DropDownList1" runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
<div class="container">
some text
</div>
</form>
</body>
</html>
more specifically this is the function im trying to run
<script type="text/javascript">
const add = (param) => {
alert("hi");
$("div.auto-style1").append("<p>'" + param + "'</p>");
}
</script>
im trying to call this function from the C# code behind the page like this
protected void Button1_Click(object sender, EventArgs e)
{
String p = "this is a message";
ScriptManager.RegisterClientScriptBlock(this, GetType(), "myfunction", "add('" + p + "');", true);
}
如果我尝试运行在页面上生成控制台日志或警报的 JS 函数,它可以正常工作。可能和 ASP 按钮中的Postback 属性有关?
如果有人能对此有所了解,我将不胜感激。
【问题讨论】:
-
您的问题中没有
auto-style1类的元素。另外,请确保在页面上呈现元素之前没有调用add(),或者将其包装在$(document).ready()函数中 -
是的,我已经更正了这一点并尝试了 $(document).ready() 包装,但仍然无法正常工作,还有其他想法吗?
-
你可以用这个做一个 MRE,这将有助于得到答案
-
如果您已经更正并放入 doc.ready,请在您的问题中显示,以便我们将其排除。
add函数何时被调用?单击按钮或页面加载?它是从哪里调用的?
标签: javascript c# html jquery