Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I pass a parameter directly to a .js file, and how do I get the value [duplicate]

I want to pass a parameter to some javascript using a single line of code, like this:

<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"?

Thanks

like image 763
jeph perro Avatar asked Jun 30 '10 00:06

jeph perro


People also ask

How do you pass a value from one js file to another?

In JavaScript, variables can be accessed from another file using the <script> tags or the import or export statement. The script tag is mainly used when we want to access variable of a JavaScript file in an HTML file. This works well for client-side scripting as well as for server-side scripting.

Does JS pass by reference or value?

JavaScript is always pass-by-value. This means everything in JavaScript is a value type and function arguments are always passed by value. That being said, object types are a bit more confusing. The confusion lies in the fact that object types are reference types which are passed by value.

Can you pass a variable to JavaScript?

Javascript pass by value:In javascript pass by value, the function is called by directly passing the value of the variable as the argument. Therefore, even changing the argument inside the function doesn't affect the variable passed from outside the function.

How are objects passed in JavaScript?

In JavaScript, object references are values. Because of this, objects will behave like they are passed by reference: If a function changes an object property, it changes the original value. Changes to object properties are visible (reflected) outside the function.


2 Answers

That's as far only possible by accessing "own" <script> element in the HTML DOM and parse the src attribute.

Long story short, here's a nice article with detailed explanations and code samples: http://feather.elektrum.org/book/src.html

like image 161
BalusC Avatar answered Sep 19 '22 12:09

BalusC


Why not just create the variable in inside a script tag before including the javascript file?

<script type="text/javascript">
    var subj = "MATH";
</script>
<script language="JavaScript" src="courselist.js" type="text/javascript"></script>
like image 45
okalex Avatar answered Sep 17 '22 12:09

okalex