gpt4 book ai didi

c# - ASP.NET 用户控件中的 Javascript 函数

转载 作者:可可西里 更新时间:2023-11-01 01:55:34 25 4
gpt4 key购买 nike

我用 javascript 函数创建了 ASP.NET 用户控件:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="TestControl.ascx.cs" Inherits="BingTranslator.Web.WebUserControl1" %>
<script type="text/javascript">
function example() {
alert('<%=ExampleButton.ClientID%>');
return false;
}
</script>
<asp:Button ID="ExampleButton" runat="server" Text="Example"/>

我想在用户将鼠标移动到按钮时调用“example”函数,所以我为按钮添加了属性:

ExampleButton.Attributes.Add("onmouseover", "example()");

它运行良好,但是当我需要在同一个页面上使用两个控件时,我遇到了问题。 ASP.NET 生成具有两个同名函数的代码,错误是什么:

<script type="text/javascript">
function example() {
alert('TestControl1_ExampleButton');
return false;
}
</script>
<input type="submit" name="TestControl1$ExampleButton" value="Example" id="TestControl1_ExampleButton" onmouseover="example()" />


<script type="text/javascript">
function example() {
alert('TestControl2_ExampleButton');
return false;
}
</script>
<input type="submit" name="TestControl2$ExampleButton" value="Example" id="TestControl2_ExampleButton" onmouseover="example()" />

并且任何按钮上的 onmouseover 事件都会调用第二个函数。我可以通过将带有客户端 ID 的 Java 脚本代码直接添加到 attriburte onmouseover 来解决这个问题。

ExampleButton.Attributes.Add("onmouseover", "[Here will be javascript code]");

但对我来说这不是很和谐的解决方案。请告知,我如何才能更好地解决此类问题。

附言会有更多的 Javascript 代码,我在上面添加了两个字符串作为示例。

最佳答案

我在另一个站点找到了一个允许您使用外部文件的解决方案

if (!Page.ClientScript.IsClientScriptIncludeRegistered("key"))

{

string url = ResolveClientUrl("~/Scripts/file.js");

Page.ClientScript.RegisterClientScriptInclude("key", url);

}

关于c# - ASP.NET 用户控件中的 Javascript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4416705/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com