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

后端 未结 5 1353
再見小時候
再見小時候 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%>';
    

提交回复
热议问题