$('#<%=nameLabel.ClientID%>') does

2020-05-01 09:52发布

问题:

$('#<%=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 it is evaluated to $('#ctl00_contentPanel1_nameLabel') properly, i can see it while debugging scripts.

however , when i keep the same script in .js file it does not evaulate to $('#ctl00_contentPanel1_nameLabel') hence does not work.

It is sure that .js script is loaded as i can debug & some other functions also work. I am using ScriptManagerProxy.

Please help ?

Thanks in advance.

回答1:

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%>';


回答2:

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.



回答3:

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



回答4:

Server code does not work in external js files.



回答5:

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')