Why doesn't this work? jquery javascript
$(document).ready(function() {
musicList = new array()
counter = 0;
if($(".rA, .trA, .dA, .hA").length > 0)
{
/*$(".rA, .trA, .dA, .hA").each(function(e){*/
$(".hA开发者_StackOverflow中文版").each(function(e){
$.post("/index/audio/ajax.track", { id: $(this).attr("rel") },
function(data){
/*THIS DOESN'NT WORK */
musicList.push(data.file);
/*THIS DOESN'NT WORK */
alert(data.file);/*this words*/
}, "json");
counter++;
});
if(counter>0)
{
alert(counter);
}
}
});
I don't see anything wrong with the code but I have no idea why it won't work I just spent 3 hours trying to get it to work
/edit/ fixed it... the push was working the alert(counter) was a little dumb of me cause of ajax = async
thanks everybody
- Declare the variables before you use them
- Always end statements with
;
. - Ditch the first if-statement, it doesn't add anything
- You can use
$(f)
instead of$(document).ready(f)
if you want - You can use
[]
instead ofnew Array()
if you want
The problem with your code is probably that the function you pass to $.post
is being run later on, but control is returned right away, so when you get to the line starting with if(counter>0)
, the function has never been executed. You can solve this by incrementing a variable each time you call $.post, when you get data back you decrement and check if all posts have returned and if so you do what you want to do. Example:
//...
var list = [];
var counter = 0;
$(".something").each(function() {
counter++;
$.post("http://www.example.com/", {foo = "bar"}, function(data) {
list.push(data);
counter--;
if(counter === 0){
alert(list.length);
};
})
});
//...
精彩评论