Script does not work with Ajax-loaded content

I have a voting system using jquery, and elements on other pages are loaded via ajax, but for the content loaded by ajax, an updated page for voting to be processed is required for voting in jquery.

http://ohmygosh.vr.lt/

I think the problem is with the actions in this file (?) But I'm not quite sure. I have no code to start with, since I don’t even know where to start. How to fix this problem?

+4
source share
1 answer

You seem to be using SmartAjax to load the contents of the page. What SmartAjax does is that it changes the URL of the page (using pushState or hash), loads the data, and REPLACES the contents of the #posts div with the loaded content.

The problem is that you are listening for click events from DOM elements that are subsequently deleted and replaced with new DOM elements. This way click events from the loaded ajax content are not listening. live() in this case will not help.

To fix this, you have at least these two options:

1) Use jQuery delegate() to attach a handler and use the #posts div as the root element, as it remains after the new content is loaded.

Something like this should work:

 $('#posts').delegate(':input', 'click', function() { var value = $(this).val(); alert('You have clicked thumbs up/down, value: ' + value); return false; }); 

2) Add a click download to the downloaded items after the data download is completed.

Note. By running jQuery 1.7 you should use on() instead of delegate()

+3
source

Source: https://habr.com/ru/post/1380192/


All Articles