简体   繁体   中英

Binding an event to an element in a view returned by ajax on success

I have a button that maes an AJAX request and fills a div with the view that is returned. Then I would like it to bind 1 click event to a button that is a DOM elements inside the view that is returned.

This is my handler for the first AJAX call that gets a view back.

// gets the next question or video
$("#next").click(function(e){
    e.preventDefault();

    $.ajaxSetup({
        headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
    });

    var host = "http://" + window.location.hostname;

    $.ajax({
        type: "POST",
        url : host + "/next",
        success : function(data){
            console.log(data);
            $('#test-content').html(data);
            $("#submit-question").bind('submit', attempt(e));
        }
    },"json");
});

This is the attempt() function that I want to attach to the event. This makes it so I can make another AJAX call from a form. Or at least I thought it would.

function attempt(e){

      e.preventDefault();

      $.ajaxSetup({
         headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
      });

      // input data
      var question_id = $('input:hidden[name=question_id]').val();
      var attempt =  $("input[name=attempt]").val();

      var dataString = 'question_id='+question_id+'&attempt='+attempt;

      var host = "http://" + window.location.hostname;

      $.ajax({
          type: "POST",
          url : host + "/attempt",
          data : dataString,
          success : function(data){
          console.log(data);
              $('#show-answer').html(data);
              $('#next-button').show();
          }
      },"json");

 }

So my problem is that, can't figure out why, but the attempt() function runs instantly after the first ajax call is made. And it never binds the event to the button. The ajax calls are made one after another with no delay. Also not sure if I could just put e in the attempt() call like I do.

You are calling attempt, not assigning it

$("#submit-question").bind('submit', attempt(e));

needs to be

$("#submit-question").bind('submit', attempt);

You could also just avoid assigning each time the html is changed. You can use event delegation and capture the submit event further up the DOM tree.

$('#test-content').on("submit", "#submit-question" , attempt);

If I am reading this right, try this:

 $('#test-content').html(data);
 $("#test-content").on('submit','#submit-question',function(){ attempt(e)});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM