$('#<%= nameLabel.ClientID%>')在.js文件中不起作用,而在脚本在页面中时起作用 [英] $('#<%=nameLabel.ClientID%>') does not work when in .js file and works when in script is in the page

查看:80
本文介绍了$('#<%= nameLabel.ClientID%>')在.js文件中不起作用,而在脚本在页面中时起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$('#<%=nameLabel.ClientID%>')正在我的jquery脚本中使用.

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

当它在tha页面的...块中时,它可以正常工作,因为它的内容页面被正确评估为$('#ctl00_contentPanel1_nameLabel'),我可以在调试脚本时看到它.

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.

但是,当我在.js文件中保留相同的脚本时,它不会散布到$('#ctl00_contentPanel1_nameLabel'),因此无法正常工作.

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

请确保已加载.js脚本,因为我可以调试&其他一些功能也可以使用. 我正在使用ScriptManagerProxy.

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

请帮助?

谢谢.

推荐答案

在.js文件中不起作用的原因有两个.

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

  • JavaScript文件未通过ASP.NET引擎运行,因此服务器标签<%= ...%>从未执行. (如果您完全控制IIS,则可以注册要由引擎运行的文件,但是由于第二个原因,它仍然无法工作.)

  • 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.)

.js文件是与页面分开请求的,因此您要获取其ID的服务器控件已不存在.它仅在处理主页请求时存在.

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.

您可以放置​​代码以将ID分配给页面中的变量,然后在.js文件中使用该变量:

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

这篇关于$('#&lt;%= nameLabel.ClientID%&gt;')在.js文件中不起作用,而在脚本在页面中时起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆