Javascript 我可以将参数直接传递给 .js 文件吗,以及如何获取值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3145650/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can I pass a parameter directly to a .js file, and how do I get the value
提问by jeph perro
I want to pass a parameter to some javascript using a single line of code, like this:
我想使用一行代码将参数传递给某些 javascript,如下所示:
<script language="JavaScript" src="courselist.js?subj=MATH" type="text/javascript" />
Inside the javascript file, how can I get the value of the parameter "subj"?
在 javascript 文件中,如何获取参数“subj”的值?
Thanks
谢谢
采纳答案by BalusC
That's as far only possible by accessing "own" <script>element in the HTML DOM and parse the srcattribute.
这只能通过访问<script>HTML DOM 中的“自己的”元素并解析src属性来实现。
Long story short, here's a nice article with detailed explanations and code samples: http://feather.elektrum.org/book/src.html
长话短说,这里有一篇很好的文章,里面有详细的解释和代码示例:http: //feather.elektrum.org/book/src.html
回答by okalex
Why not just create the variable in inside a script tag before including the javascript file?
为什么不在包含 javascript 文件之前在脚本标记内创建变量?
<script type="text/javascript">
var subj = "MATH";
</script>
<script language="JavaScript" src="courselist.js" type="text/javascript"></script>
回答by Earlz
The only way to get something like this to work is to have the server serving up a dynamically generated javascript file where it has something like this on the server:
使这样的事情工作的唯一方法是让服务器提供一个动态生成的 javascript 文件,它在服务器上有这样的东西:
if(Parameters["subj"]=="MATH"){
jsfile="var subj='MATH'; "+jsfile;
}...
回答by kennebec
When a script, loaded from a script src file is interpreted, its related script element exists in the document.
当解释从脚本 src 文件加载的脚本时,其相关的脚本元素存在于文档中。
Don't worry about which file is which- look at everyscript element for an url with a query string.
不要担心哪个文件是哪个 - 查看带有查询字符串的 url 的每个脚本元素。
回答by Elias Zamaria
I don't think the Javascript file would be aware of the parameter that is passed to it. If that address goes to some sort of server-side script (NOT just a static Javascript file), then you may be able to do something with it.
我认为 Javascript 文件不会知道传递给它的参数。如果该地址进入某种服务器端脚本(不仅仅是静态 Javascript 文件),那么您也许可以用它做一些事情。

