$('#<%=nameLabel.ClientID%>') does not work when in .js file and works when in script is in the page

后端 未结 5 1303
再見小時候
再見小時候 2021-01-28 19:08

$(\'#<%=nameLabel.ClientID%>\') is being used in my script for jquery.

When this is in ... block in tha page , it works fine ,as its a content page i

相关标签:
5条回答
  • 2021-01-28 19:34

    There are two reasons that this doesn't work in a .js file.

    • Javascript files are not run through the ASP.NET engine, so the server tag <%=...%> is never executed. (If you have full control over the IIS you can register the files to be run by the engine, but it still won't work because of the second reason.)

    • The .js file is requested separately from the page, so the server control that you want to get the id for doesn't exist any more. It only exists while the request for the main page is handled.

    You can put code to assign the id to a variable in the page, and use that variable in the .js file:

    var nameLabel = '#<%=nameLabel.ClientID%>';
    
    0 讨论(0)
  • 2021-01-28 19:38

    Like the others have explained <%=nameLabel.ClientID%> needs to run on the server. You could however do something like this:

    $("[id$=_nameLabel]")
    

    Checks all ids and matches those that end with _nameLabel.

    0 讨论(0)
  • 2021-01-28 19:38

    Simple answer : You can't use inline asp.net scripting in external .js files.

    But there are two articles and source code which make this possible :

    Simply click here and click here.

    And also Asp.NET 4.0 brings a nice solution to this problem which is called ClientIDMode

    Markup: <asp:TextBox ID="txtEcho2" runat="server" ClientIDMode="Static" /> 
    Output: <input id="Text1" name="ctl00$MasterPageBody$ctl00$txtEcho2" />
    

    Markup: <asp:TextBox ID="TextBox1" ClientID="Echo" runat="server" ClientIDMode="Static" /> 
    Output: <input id="Text2" name="Echo" />
    

    Markup: <asp :TextBox ID ="txtEcho" runat ="server" ClientIDMode ="Legacy" />  
    Output: <input id="ctl00_MasterPageBody_ctl00_txtEcho" name="ctl00$MasterPageBody$ctl00$txtEcho" />
    

    For more information, drop by here

    0 讨论(0)
  • 2021-01-28 19:53

    Server code does not work in external js files.

    0 讨论(0)
  • 2021-01-28 19:53

    External javascript files are not served by the ASP.NET engine, so any server side tags such as <%= ... %> will not work. You could apply a css class to the element and use a CSS selector:

    $('.nameLabel')
    
    0 讨论(0)
提交回复
热议问题