JQuery code does not apply to form when form is rendered via AJAX

I have a pretty standard voice voting feature in my application that uses the jQuery hover event. In part, the star voting logic is used to render with the rest of the page after the initial loading of the DOM (HTML request). However, I would like to move the partial so that it does not load using the page, but can be loaded when the user wants. I made a typical AJAX request to download a partial one, but when it receives a render, the stars do not respond properly to events such as mouse hover. Does this problem occur because I process forms via AJAX or is there just an error in my code? thanks for the help

Update: it worked with a handler, thanks for the help!

+3
source share
5 answers

You are probably trying to associate events with nodes that do not yet exist in the DOM. The best way to solve this problem is to associate with the listener that exists before the Ajax request, which is the ancestor (sometimes incorrectly called the "parent", which is only one level of the ancestor) of the received content. For example, given this markup on the page itself:

<div id="ajaxContainer">
  <!-- content will be periodically replaced with Ajax -->
</div>

"ajaxContainer" , . . live(), . delegate(), . on(), , delegate(), .

, , .on(), jQuery 1.7 +.

, Ajax , , divs, "". :

$(document).ready(function() {
  $('#ajaxContainer').on('mouseenter', '.stars', function() {
    $this = $(this); // cache this specific instance of a stars div as a jQuery object
    // do stuff with $this
  });
});

: " ajaxContainer , " , divs ", , -".

+3

, Ajax, , , DOM .

, DOM, .

on() :

$('#nonDynamicElement').on('mouseenter', '#dynamicElement', function() {
    //do stuff
});
+2

jQuery live, .

, on().

0

jQuery 1.7+, on() jquery live()

0

jQuery AJAX script, jQuery $.

jQuery( selector [, context] )

$( selector [, context] ) 
-1
source

All Articles