Possible Duplicate:
jQuery .data() Not Updating DOM
I am having a problem with using the on attribute. I have written a small set of methods to send api calls.
The markup is like this:
<div data-global-id="1318" data-action="unfollow" class="action text-as-link follow-btn btn" style="text-decoration: none;">unfollow</div>
and have an event capture like this:
$(document).on('click','.action', function(){
var t={};
t.args={};
t.args.global_id=$(this).data('global-id');
t.global_id=t.args.global_id;
t.action=$(this).data('action');
t.identifier=t.action + '_v2';
alert('here is action: ' + t.action);
api_post_v1(t);
});
The api_post_v1 correctly sends the call.
There is some code to handle the callback and it sets the markup to:
<div data-global-id="1318" data-action="follow" class="action text-as-link follow-btn btn" style="text-decoration: none;">follow</div>
The code for this is like:
$foo=$('.action[data-action=unfollow][data-global-id='+global_id+']');
$foo.attr('data-action','follow');
The key piece is the data-action. I’d like the call to the event handler above to say it is ‘follow’ but it says it is still ‘unfollow’.
The sequence is the following:
- load page, the data-action=’unfollow’
- click this, api call gets made and you are not following this user; the callback sets data-action=’follow’
- click this value again and the data-action is echoed as ‘unfollow’ rather than ‘follow’
How could I tell jQuery to refresh the bindings of this event? I thought this was what $(document).on does.
thx
The
data-*attributes & jQuery’s.data()method are not interchangeable. Use this to get it:You seem to be mixing jQuery’s
datamethod with HTML5’sdata-*attributes. These are two different things. The only time they interact with one another is when you first call.dataon an element.When you make a call to
.data, jQuery looks for anydata-*attributes, and adds it to thedatacollection. However, this only happens once. Subsequent calls to.datawill not look at the element’sdata-*attributes.To quote the jQuery docs:
Since you’re using
.attr('data-action', 'follow')to set it, you should use.attr('data-action')to get it.Note:
$('.action[data-action=unfollow]')will not select an element that had theactionset via jQuery’s.data. Again, the two are not interchangeable.