Why doesn't Javascript let me close up my function?
I dunno guys, this is a really weird one, but I might just be making a simple mistake and not even realizing it.
I'm sort of a newbie to Javascript, so I'm attempting to write a script that gets content fro开发者_JAVA技巧m a PHP script (which returns only a number) and write that data to a div... but Javascript had other ideas. I'm testing on Chrome on Mac OS X, although it doesn't work on Safari either.
The following block is giving me problems:
function getContent() {
window.setInterval(function () {
$.get("get.php", function (data) {
$('#img').slideUp();
$('#div').html(data);
$('#div').slideDown();
}
}
}
Which is failing with:
Uncaught SyntaxError: Unexpected token }
on line 51
, or line 8
, for the purposes of this example.
Does anyone know why it would fail like this? Don't I need to close the brackets I open?
Your curly braces are OK, but you're missing a few parentheses:
function getContent() {
window.setInterval(function () {
$.get("get.php", function (data) {
$('#img').slideUp();
$('#div').html(data);
$('#div').slideDown();
}); //get - end statement
}, 4000); // setInterval - need another parameter, end statement
}
You're not closing the parentheses for your function calls. As Kobi said, you also need a third parameter for setInterval
.
function getContent() {
window.setInterval(function () {
$.get("get.php", function (data) {
$('#img').slideUp();
$('#div').html(data);
$('#div').slideDown();
});
}, 1000);
}
The window.setInterval function has a following syntax:
window.setInterval(functionRef, timeout);
In your case the setInterval
and $.get()
function call are missing the closing parentheses )
. It would be clear for you to write this in the following way:
function getContent() {
// success handler
var success = function() {
// declare the function first as "changeUI"
var changeUI = function() {
$('#img').slideUp();
$('#div').html(data);
$('#div').slideDown();
};
// call the setInterval passing the function
window.setInterval(changeUI, 2000);
};
// get the resource and call the "success" function on successful response
$.get("get.php", success);
}
your window.setInterval is missing a ) after the } on the second to last line
精彩评论