Add class into html tag by JQuery in ASP.NET C#

廉价感情. 提交于 2019-12-25 03:07:14

问题


I tried to add class in tag

  • but when the web form postback it lost :(
    <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

  • 标签
    易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
    该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!