I have two types of links that are event-bound. If the clicked-on link has the class 'flagged', the event handler calls recallFlag, else doFlag function.
$(document).ready(function() {
$('div.flag-link, span.flag-link').bind('click', function(e){
if ($(e.target).attr('class')=='flagged') doRecall(e);
else doFlag(e);
return false;
});
The doFlag function loads a form, and when the user submits it, receives json data. Using that data, it changes the link's href and class (flagged-->unflagged and vice-versa).
When the user flags an item for a first time, the execution is ok. But when for a second time the user clicks on a different link to flag another item, I have a weird behavior: event.target is changed to the first element (that was clicked at the first time) inside the callback function of the post event. As a result, a wrong link (the link that was clicked previously) is updated.
What am I doing wrong?
function doFlag(e) {
var link = e.target;
var $prnt = $(link).parent();
var $url = $(link).attr('href');
console.log('new attempt to flag:' + $(link).attr('href'));
Boxy.load($url, {modal:true, title:e.target.innerHTML, closeText:'[Kapat]', unloadOnHide:true, cache:false, behaviours: function(r) {
$("#flag-form-submit").live("click", function(){
var post_url = $("#flag-form").attr('action');
$.post(post_url, $("#flag-form").serialize(), function(data){
//THIS IS WHERE THE CODE SCREWS UP:
//here "link" is changed to the former link that triggered the event previously
if (data.status == 'ok') {
$(link).attr('href', data.url);
$(link).attr('class', data.css_class);
$(link).attr('innerHTML', data.text);
$prnt.children('img.flag-img').css('visibility', 'visible');
}
}, "json");
boxy = Boxy.get(this);
boxy.hideAndUnload();
return false;
});
}
});