Imagine we have the following code in an HTML file:
<script id='tag-1'>
function foo(){
alert("this is foo-1");
}
</script>
<script id='tag-2'>
function foo(){
alert("this is foo-2");
}
</script>
<script id='tag-3'>
function foo(){
alert("this is foo-3");
}
</script>
Is it possible to invoke function foo
from the script tag with id tag-2
?
I'm just curious to know if there is any cross-browser solution? Thank's guys.
Ok we have two very relevant proposals - the one that I marked for accepted answer and another one of the comments rigth below this post - the one that @dfsq propose. Thank you all guys!!!
The first method is to call the JavaScript function in HTML. For this, you have to create a function then define this function either in the head section or body section of the HTML document. You can either create a link or a button and then an onclick() event is associated with them in order to call this function.
The <script> tag is used to embed a client-side script (JavaScript). The <script> element either contains scripting statements, or it points to an external script file through the src attribute. Common uses for JavaScript are image manipulation, form validation, and dynamic changes of content.
To include an external JavaScript file, we can use the script tag with the attribute src . You've already used the src attribute when using images. The value for the src attribute should be the path to your JavaScript file. This script tag should be included between the <head> tags in your HTML document.
No, that's not possible without resorting to eval()
.
As each script block is evaluated by the browser the previous versions of the function are overwritten.
You can access the text context of each <script>
tag, but only if it's inline. Accessing the source of <script src="...">
tags requires AJAX.
Yes this is totally possible, but you should use a type other than text/javascript.
<script id='tag-1' type="myScriptHolder">
function foo(){
alert("this is foo-1");
}
</script>
<script id='tag-2' type="myScriptHolder">
function foo(){
alert("this is foo-2");
}
</script>
<script id='tag-3' type="myScriptHolder">
function foo(){
alert("this is foo-3");
}
</script>
<script>
$.globalEval($('#tag-1').text();
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With