Could not access asp.net control ID in jquery

前端 未结 2 1415
梦如初夏
梦如初夏 2020-12-21 12:10

I have this html structure:


  
相关标签:
2条回答
  • 2020-12-21 12:56

    My similar answer with a little more explanation is here

    runat="server" in asp.net adds master and page information to each of its control. So, if you look at the DOM, your control would look something like this master_page_ctrl0_specialId[just an example].

    You have a few options.

    Option1: Use the client ID - recommended but meh.. not so much. I would try to avoid writing ClientID in javascript as much as possible.

    $('#<%= specialId.ClientID %>')
    

    Option2: Using the same ID - not recommended because its really ugly.

    $('[id$=specialId]') or $('[id*=specialId]')

    The above selectors are any id which ends with specialID and any id which contains specialId respectively.

    Option3: Using the class - highly recommended. Because selectors using classes are clean and uncomplicated. Also, I see you've used class, use CssClass instead for .net controls.

    $('.ClassOne.ClassTwo')
    

    Option4: Use ClientIDMode="Static", which got introduced in .NET Framework 4.0, on the control so that its ID will stay unchanged. - recommended too.

    <asp:Panel runat="server" ClientIDMode="Static" id="specialId" CssClass="ClassOne ClassTwo">
    </asp:Panel>
    
    0 讨论(0)
  • 2020-12-21 12:56

    You should use actual generated HTML id using below syntax

    That means you need to use client ID which can be accessed via below syntax

    $('#<%= specialId.ClientID %>')
    
    0 讨论(0)
提交回复
热议问题