从外部 JS 文件引用 ASPX 控件
我有一个问题。我有一个 aspx 控件(例如文本框)。我使用 document.getElementById('<%=textbox.ClientID%>').value 引用它。当我将代码放在同一个 aspx 文件中时,它就可以工作。但一旦从外部文件(例如 MyJSFunctions.js)引用它,我就不能了。我收到一条错误消息,说“该对象不存在或为空”,
我已经包含了 js 文件的名称,就像
我这样做一样,因为我喜欢将所有 js 函数放在一个单独的文件中,这样做也可以减少负载开销。
为什么会发生这种情况?我可以使用 jquery 完成同样的任务吗?
I have a question. I have a aspx control (for e.g textbox). I reference it using document.getElementById('<%=textbox.ClientID%>').value. When I have the code in the same aspx file it works. But as soon reference it from an external file (example MyJSFunctions.js), I cannnot. I get an error saying "the object does not exist or it is null"
I have included the name of the js file like
I did this because I like having all my js functions in a seperate file nad doing this also reduces the load overhead.
Why is this happening? Can I accomplish the same using jquery?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要对 Javascript 进行参数化以接受所需的参数,然后将内联 ASP.NET 脚本在服务器端页面或控件中作为此类值传递。这将允许引擎适当地渲染内联代码。
发生这种情况是因为服务器在将页面推送至客户端 - 这只会发生在“注册”类型上,并且不(也不应该)包含 Javascript 文件(尽管您可以技术上注册要处理的项目,除非您有定制模块处理内联脚本的编译Javascript 中,那么无论如何它都会出错。)
jQuery 本质上是 Javascript 框架的一部分,可以说,您与它处于同一条船上。
作为示例,请考虑以下内容...
您的脚本文件:
您的 ASPX 页面:
You will need to parametise your Javascript to accept the desired argument, then pass the inline ASP.NET script within the server-side page or control as the value of such. This will allow the engine to render the inline code appropriately.
It happens because the server renders your pages (not in the sense of a browser rendering HTML, but rather the ASP.NET engine making transformations to turn your .NETified web mark-up into standard web mark-up) prior to pushing them down to the client - this will only happen for "registered" types, and that doesn't (and shouldn't) include Javascript files (although you can technically register items to handle, unless you have a bespoke module to handle compilation of inline scripting among Javascript, then it would err anyway.)
jQuery essentially being something of a Javascript framework, you're in the same boat with that, so to speak.
As an example, consider the following...
Your script file:
Your ASPX page:
您可以做的一件事是在您的 ASPX 页面中添加以下 Javascript 代码:
然后,在您的外部 JS 文件中(确保这是在上面的行之后):
另一种选择是在ClientID 到您的代码中,但请注意,如果您将来更改该文本框控件的 ID 或父容器,则会破坏它。
One thing you could do is have the following Javascript code in your ASPX page:
Then, in your external JS file (make sure this is after the above line), have:
Another alternative is just hardcode in the ClientID into your code, but note you'll break it if you change the ID or parent container of that textbox control in the future.