neda Derakhshesh neda Derakhshesh - 4 months ago 13
Ajax Question

In self invoking function expression (closures) , result is same always

I have a self invoking function Expression in a ajax call

$("#helpicons li").click(function () {
var self = this;

$.post('/SubCategories/GetSubCat/' + $(self).data('id'), function (data)
{

for (var i = 0; i < data.length; i++)
{
var helplist = data[i];

$('<li/>').html("<h5>" + helplist.scat + "</h5>" +"<ul id='qlist'></ul>").appendTo('#taglist');



$.post('/Questions/GetQuestion/' + helplist.scatid, function (dd)
{
for (var j = 0; j < dd.length; j++)
{
var helpquestion = dd[j];

(function () {

$('<li/>').html("<p>" + helpquestion.quest + "</p>")
.click(function () {

alert(helpquestion.quest);//Problem is here

}).appendTo('#qlist');

})();
}
});
}
});

});


but when click on each
<li>
in
<ul id="qlist">
the result in alert is the last row of data in my database and same for all the li tags in list. it seems self invoking is not working .

My Actions if needed:

[HttpPost]
public JsonResult GetQuestion(int id)
{
var ajaxq = db.Questions.Where(e => e.SubCategoryId == id).Select(e => new
{
quest=e.Qu,
answe=e.Ans
}).ToList();

return Json(ajaxq);
}


and

[HttpPost]
public JsonResult GetSubCat(int? id)
{
//:TODO
if (id == null)
{
//return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}


var result = db.SubCategories.Where(e => e.CategoryId == id).Select(e => new
{
scat = e.SubCategoryName,
scatid = e.Id

}).ToList();

Answer

You can change your event handler to look at the current item rather than try to hold on to some variable:

$('<li/>').html("<p>" + helpquestion.quest + "</p>")
    .click(function () {

            alert($(this).text())

    }).appendTo('#qlist');