I'm trying to turn display Mysql queries results on a click event. The results may be different, depending on the link that is clicked. So I've thought adding a FOR loop inside my click function. It seems I'm wrong with my code :
<script src="http://yui.yahooapis.com/3.8.1/build/yui/yui-min.js"></script>
<script>
YUI().use("node", function (Y) {
for (var i=1; i<4; i++) {
Y.one("#link" + i).on('click', function ajaxFunction(i){
var id = document.getElementById("link" + i).className;
Y.io('query.php',
{
type: "GET",
data: "id="+id,
success: function (msg) {
Y.one("#display_div" + i).setHTML(msg);
}
});
});
};
});
</script>
<a href="#" id="link" class="(Test 1)"> Maths</a>
<div id="display_div1"></div>
<a href="#" id="link" class="FAQ"> Anglais</a>
<div id="display_div2"></div>
This code is an translation in YUI3 of my working jQuery code :
<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
<script languid="javascript" type="text/javascript">
$(document).ready(function() {
for (var i=1; i<4; i++) {
$("#link" + i).click(makeDisplayCallback(i));
}
});
function makeDisplayCallback(j) {
return function() {
ajaxFunction(j);
};
}
function ajaxFunction(j){
var id = document.getElementById("link" + j).className;
$.ajax(
{
type: "GET",
url: "query.php",
data: "id="+id,
success: function (msg) {
$("#thema" + j).html(msg);
}
});
};
</script>
You're running into a classical example of how references work in JavaScript. When the success
callback is called, the value of i
is always 2
because it already changed to the next iteration. What you need to do is wrap each callback in another function so each of them points to a different value of i
.
for (var i = 1; i < 3; i++) {
Y.io(url, {
on: {
// on each iteration the success function is a different function
success: (function (index) {
return function (msg, result) {
Y.one('#display_div' + index).setHTML(msg);
};
}(i)); // we pass it the current value of i
}
});
}