Reputation: 4501
I have read several topics on this, but the problem still persists. I have a Django template:
<tr>
{% if task.status.id == 3 %}
<td onclick = 'fulfillment_status({{task.id}}, 2)'>
<div style = 'color:green'</div>
</td>
{% else %}
<td onclick = 'fulfillment_status({{task.id}}, 3)'></td>
{% endif %}
</tr>
JS:
var fulfillment_status = function(task_id, status_id)
{
alert('sdf');
$.post('/task_list/set_task_status/' + task_id + '/' + status_id + '/', function (new_status){
if (new_status.id == 3)
{
$('#status_icon_' + task_id).children().css('color', 'green');
}
else
{
$('#status_icon_' + task_id).children().css('color', 'red');
}
$('#status_icon_' + task_id).unbind('click').click(function (e) { e.preventDefault(); fulfillment_status(task_id, new_status.id)});
});
};
Note that I've already tried to use unbind method and preventDefault. The onload function does not have anything to do with the div click event. The click event is called twice and even multiple times. Any ideas why this might happen ?
Upvotes: 0
Views: 95
Reputation: 74738
As you don't have bound any event with bind
listener, so, unbind
won't have any effect to remove the previously bound event.
From the docs:
Event handlers attached with
.bind()
can be removed with.unbind()
. (As of jQuery 1.7, the .on() and .off() methods are preferred to attach and remove event handlers on elements.) In the simplest case, with no arguments, .unbind() removes all handlers attached to the elements.
Another suggestion is to use html5's data-*
attribute to store data:
<tr>
{% if task.status.id == 3 %}
<td class='status_icon' data-task-id="{{task.id}}" data-status-id="2">
<div style = 'color:green'</div>
</td>
{% else %}
<td class='status_icon' data-task-id="{{task.id}}" data-status-id="3"></td>
{% endif %}
</tr>
Now at the js side do this:
var fulfillment_status = function(task_id, status_id) {
alert('sdf');
$.post('/task_list/set_task_status/' + task_id + '/' + status_id + '/', function(new_status) {
if (new_status.id == 3) {
$('#status_icon_' + task_id).children().css('color', 'green');
} else {
$('#status_icon_' + task_id).children().css('color', 'red');
}
});
};
$(document).ready(function() {
$('.status_icon').on('click', function(e) { // <--try adding a common class name to bind the click event.
e.preventDefault();
var task_id = $(this).data('taskId'),
new_status = $(this).data('statusId');
fulfillment_status(task_id, new_status);
});
});
Upvotes: 1