简体   繁体   English

是否可以在外部.js文件中引用我的代码隐藏变量?

[英]Is it possible to reference a variable from my codebehind in an external .js file?

I'm cleaning up some old projects and moving the javascript from my .aspx pages to an external javascript file. 我正在清理一些旧项目并将javascript从我的.aspx页面移动到外部javascript文件。

In a few of my pages, I reference variables from the C# side in my javascript. 在我的一些页面中,我在我的javascript中引用了C#端的变量。 For example: 例如:

var myVal = <%= idNumber %>;

where idNumber is a public variable set in my codebehind. 其中idNumber是我的代码隐藏中设置的公共变量。

This no longer works when I move the script to an external file, which makes sense. 当我将脚本移动到外部文件时,这不再有效,这是有道理的。 I thought explicitly stating window.idNumber might work, but I was incorrect. 我想明确说明window.idNumber可能window.idNumber ,但我不对。

Is there a way to make this work? 有没有办法让这项工作? If not, what is the best practice? 如果没有,最佳做法是什么? Should I keep the js similar to this example in the page itself and call "external" methods? 我应该在页面本身中保持js与此示例类似,并调用“外部”方法吗? Can I assign a .js file to a specific page and only that page (just to keep my code clean)? 我可以将.js文件分配给特定页面而只分配该页面(只是为了保持我的代码清洁)吗?

Any advice would be greatly appreciated 任何建议将不胜感激

I ran into this problem a while back as well. 我也回过头来讨论这个问题了。 My solution was to re-factor my JS code to use function parameters and then have my code-behind call the functions. 我的解决方案是重新考虑我的JS代码以使用函数参数,然后让我的代码隐藏调用函数。 This has the added benefit that it makes your JS code more re-usable. 这具有额外的好处,它使您的JS代码更易于重用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM