Reputation: 555
I'm woking on a ASP.NET project and im trying to use the attr function, when im putting in the script tag the src for the jquery file the function isnt being called when im calling it via c# code.
<script type ="text/javascript" src="jquery-3.1.1.min.js">
$(document).ready(function () {
function startGame(path) {
alert(path);
$("#test").attr("style", "color:Blue");
$("#game_param").attr("value", path);
$("#game_embed").attr("src", path);
}
});
</script>
I tried to write a simple javascript fucntion
<script type ="text/javascript" src="jquery-3.1.1.min.js">
function startGame(a) {
alert(a);
}
</script>
and it wasn't called either
im getting en error that startGame isn't defined, in both cases. can someone expain to me what im doing wrong?
Upvotes: 0
Views: 90
Reputation: 1373
You actually have multiple errors.
Browsers will ignore any javascript written inside a script
tag that has a src
attribute. So you need to include jQuery separately, like so:
<script type ="text/javascript" src="jquery-3.1.1.min.js"></script>
<script>
// Your code here.
</script>
You're never actually calling the function, only declaring them. If you're only going to use this once, you don't even need a function:
<script type ="text/javascript" src="jquery-3.1.1.min.js"></script>
<script>
$(document).ready(function () {
alert(path);
$("#test").attr("style", "color:Blue");
$("#game_param").attr("value", path);
$("#game_embed").attr("src", path);
});
</script>
Otherwise, you need to call the function after declaring it like so:
$(document).ready(function () {
function startGame(path) {
// Your code
}
startGame();
});
Function Declarations vs Expressions
Upvotes: 0
Reputation: 142
You need to include the jQuery source separately from your custom code. Otherwise I believe what is inside of the script tag is ignored.
<script type ="text/javascript" src="jquery-3.1.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var p = 'here/is/my/path';
function startGame(path) {
alert(path);
$("#test").attr("style", "color:Blue");
$("#game_param").attr("value", path);
$("#game_embed").attr("src", path);
}
startGame(p);
});
</script>
Upvotes: 3
Reputation: 1350
Your Javascript isn't correct.
When you do:
<script type ="text/javascript" src="jquery-3.1.1.min.js">
function startGame(a) {
alert(a);
}
</script>
You're setting the source of the JavaScript file to be the jQuery JS file. If you want to define your own functions, you have to put it in its own script
tag, like so:
<script type ="text/javascript" src="jquery-3.1.1.min.js"></script>
<script type="text/javascript">
function startGame(a) {
alert(a);
}
</script>
Upvotes: 0