javascript for loop with dynamic div id
It's happening because the AJAX callback handlers you create both share a reference to the same variable "i". To avoid that, you can create your "success" handler with a separate function edit — in fact, due to the nature of your code structure here, you need to make the whole "change" callback in a separate function:
function makeChangeHandler(listIndex) { return function() { var wdiv = $(this).val(); $.ajax({ type: "POST", url: "populate_classes.php", data: 'theOption=' + wdiv, success: function(whatigot) { $('#class_list' + listIndex).html(whatigot); } }); }; } // ... for (var i = 0; i < 2; i++) { // for 2, substitute actual number of elements involved $('#wdiv' + i).change( makeChangeHandler(i) ); }That function will return the actual handler function. Each such function returned by "makeSuccessHandler" will have it's very own private copy of the loop index.
(Note edits made - the whole "change" handler needs to be constructed in the helper function.)
2025-07-29 03:58 点击量:5