Using the jQuery 'click' function that was loaded with Ajax content?

I have the contents of a php file downloaded via Ajax that contains HTML and JavaScript. I have a button:

<button class="search_button">Search</button>

And beneath it there is a script that will update hash documents from jQuery function

<script type="text/javascript">
  $(".search_button").click(function() {
    var searchTerm = $('#search_box').val();         
    document.location.hash="searchTerm";
    return false;
  });
</script>

This code works when I run the php file separately, but when loading this page from an Ajax call, the function no longer runs. There is no script in firebug, so I assume that I cannot load the script when using this method. I also tried adding a JavaScript snippet instead of the header for the entire website, but that also failed.

, , , , search_button, , ( Ajax) , '' .

+3
3

:

  $(".search_button").live('click', function() {
    var searchTerm = $('#search_box').val();         
    document.location.hash="searchTerm";
    return false;
  });

jQuery script, HTML, . . , , . -

setTimeout(function(){  
    $(".search_button").click(function() {
        var searchTerm = $('#search_box').val();         
        document.location.hash="searchTerm";
        return false;
    });
}, 500);

, script, (, jquery DOM ).

+7

jQuery 1.7, . live() . . On() . jQuery .delegate() . live().

, , . . . On().

. live() ; :

$(selector).live(events, data, handler);                // jQuery 1.3+
$(document).delegate(selector, events, data, handler);  // jQuery 1.4.3+
$(document).on(events, selector, data, handler);        // jQuery 1.7+

. On()

$(document).on("click", "#post a", function(){
    alert("1");
})
+7

script

 

function name(){
  $(".search_button").click(function() {
    var searchTerm = $('#search_box').val();         
    document.location.hash="searchTerm";
    return false;
  });
}
 

and call this function right after the end of the ajax call.


$(document).ready(function() {
 name();
});
+1
source

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


All Articles