问题
I tried to add class in tag
<ul>
<li><asp:Linkbutton runat="server" Text="Text1"/></li>
<li class="active"><asp:Linkbutton runat="server" Text="Text2"/></li>
and this is my JQuery Code
<script>
$(document).ready(function () {
$("li").click(function () {
$("li").removeClass();
$(this).addClass("active");
});
});
</script>
回答1:
Nothing that isn't runat="server" can be persisted; you need to store information about selected element (somewhere) - either utilize which link was clicked or store id of last clicked element into hidden field:
<ul>
<li id="uid1"><asp:Linkbutton ID="Linkbutton1" runat="server" Text="Text1"/></li>
<li id="uid2" class="active"><asp:Linkbutton ID="Linkbutton2" runat="server" Text="Text2"/></li>
</ul>
<asp:HiddenField ID="hfActive" runat="server" />
<script type="text/javascript">
$(document).ready(function () {
var sId = $('#<%= hfActive.ClientID %>').val();
if (sId != "") {
$("li").removeClass();
$('#' + sId).addClass("active");
}
$("li").click(function () {
$('#<%= hfActive.ClientID %>').val($(this).attr('id'));
$("li").removeClass();
$(this).addClass("active");
});
});
</script>
Note: the "li" elements have to have unique id assigned in this case.
回答2:
<ul>
<li id="lnkbtn1" runat="server"><a href="Default1.aspx"><span>Text1</span></a></li>
<li id="lnkbtn2" runat="server"><a href="Default2.aspx"><span>Text2</span></a></li>
</ul>
In Code File
protected void Page_Load(object sender, EventArgs e)
{
setCurrentPage();
}
private void setCurrentPage()
{
var pagename = Convert.ToString(GetPageName());
switch (pagename)
{
case "Default1.aspx":
lnkbtn1.Attributes["class"] = "active";
break;
case "Default2.aspx":
lnkbtn2.Attributes["class"] = "active";
break;
}
}
private object GetPageName()
{
return Request.Url.ToString().Split('/').Last();
}
来源:https://stackoverflow.com/questions/23710337/add-class-into-html-tag-by-jquery-in-asp-net-c-sharp