所以我有一个名为 footer
的用户控件,它包含到网站的导航,我试图将 active
css 类附加到用户控件中的 div,以便用户
这是我的footer.ascx
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="Footer.ascx.cs" Inherits="UserControls_Footer" %>
<div id="bottom">
<div class="Footer navbar-fixed-bottom">
<div class="container">
<div class="row">
<button id="ImgOption1Guru" class="btn btn-large btn-block btn-primary" runat="server" type="button" onclick="location.href='Option1.aspx';">Option 1</button>
<button id="ImgCmnyInfo" class="btn btn-large btn-block btn-primary" onclick="location.href='CompanyInfo.aspx';" runat="server" type="button">Info</button>
<button id="ImgInteract" class="btn btn-large btn-block btn-primary" onclick="location.href='Interact.aspx';" runat="server" type="button">Interact</button>
<button id="ImgActions" class="btn btn-large btn-block btn-primary" onclick="location.href='Actions.aspx';" runat="server" type="button"> Actions</button>
<button id="ImgStatus" class="btn btn-large btn-block btn-primary" onclick="location.href='Status.aspx';" runat="server" type="button">Status</button>
</div>
</div>
</div>
</div>
我在我的 aspx
页面中使用了这个页脚
<div id="footer"><ucl:Footer ID="foot" runat="server" /></div>
现在我想将 css 类 active
添加到各自页面上的 button id
.到目前为止,我已经尝试将代码添加到相应的页面,但它似乎不起作用
<script type="text/javascript">
var x = document.getElementById("ImgActions");
x.classname += " " + active;
</script>
我应该怎么做才能在我的 aspx 页面中访问用户控件中的标签 ID。
最佳答案
您需要使用控件的ClientID
,因为当您没有ClientIDMode 时,当asp.net 生成html 时控件的id 将被更改。未设置为 static
。 classname
也应该是 className
var x = document.getElementById("<%= ImgActions.ClientID %>");
x.className += " " + active;
ASP.NET provides multiple algorithms for how to generate the ClientID property value. You select which algorithm to use for a control by setting its ClientIDMode property. The algorithms are identified by the ClientIDMode enumeration, Reference.
您可以使用 ClientIDMode static,因为您在不同的控件中使用了 javascript,而这些控件不知道 ImgActions。
HTML
<button id="ImgActions" ClientIDMode="static" class="btn btn-large btn-block btn-primary" onclick="location.href='Actions.aspx';" runat="server" type="button"> Actions</button>
Javascript
var x = document.getElementById("ImgActions");
x.className += " " + active;
关于javascript - 从 aspx 页面中的 usercontrol 访问一个 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19947256/