jquery ajax item can not be clicked after reload

余生颓废 提交于 2019-12-01 23:28:00

问题


I am using django

In the body block

<div id="tag_like">
    {% if liked %}
      <img id="unlike" title="unlike" src="{{ STATIC_URL }}pic/bad.png" />
    {% else %}
      <img id="like" title="like" src="{{ STATIC_URL }}pic/good.png" />
    {% endif %}
</div>

In the on_ready script block:

$.ajaxSetup({
  data: {csrfmiddlewaretoken: '{{ csrf_token }}'},
});
$('#like').click(function() {
   $.post("{% url 'likevideo' %}", {uid:{{ login_id }}, videoid:"{{ videoid }}"}, function(data,status){
      $('#tag_like').load(' #tag_like')
   });
});
$('#unlike').click(function() {
   $.post("{% url 'unlikevideo' %}", {uid:{{ login_id }}, videoid:"{{ videoid }}"}, function(data,status){
      $('#tag_like').load(' #tag_like')
   });
});

It works fine at the 1st time you click the image.(turned to the other image) But when click it again, no ajax action happens. I read

Refresh a div in Django using JQuery and AJAX

jqgrid not reloading after making a ajax call using trigger('reload')

Adding jQueryui Buttons to dynamically added content

But no specific solution reached yet... Any solution with minimal changes?


回答1:


try this for event binding:

$('#tag_like').on("click", "#like", function() {
   $.post("{% url 'likevideo' %}", {uid:{{ login_id }}, videoid:"{{ videoid }}"}, function(data,status){
      $('#tag_like').load(' #tag_like')
   });
});
$('#tag_like').on("click", "#unlike", function() {
   $.post("{% url 'unlikevideo' %}", {uid:{{ login_id }}, videoid:"{{ videoid }}"}, function(data,status){
      $('#tag_like').load(' #tag_like')
   });
});



回答2:


Use .on() because you are loading DOM to div with ID of tag_like.

$(document).on('click','#like',function(){
    //code here.
});



回答3:


Do it like:

$('#tag_like').on("click", "#like", function() {
   $.post("{% url 'likevideo' %}", {uid:{{ login_id }}, videoid:"{{ videoid }}"}, function(data,status){
      $('#tag_like').load(' #tag_like')
   });
});

This method is fast because it will prevent jQuery from parsing whole document each time you click on the button.



来源:https://stackoverflow.com/questions/16162886/jquery-ajax-item-can-not-be-clicked-after-reload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!