1

I want to use jquery .on() to do the AJAX

Anyway,I test two method below,both of them works
I want to know what's the difference between them??
are the both method correct?

<script type="text/javascript">
/*method 1*/
/*$(document).on('submit', '.login-form', function(){ */
$(document).on('click', '.searchtitle', function(){
    ttest = $(this).serialize();
    console.log(ttest);    
});
/*method 2*/
$(".searchtitle").on('click',   function(){
    ttest = $(this).serialize();
    console.log(ttest);    
});
</script>

test.html
<form action="" method="post"  class="searchtitle">
    {% csrf_token %}
    search activity :<input type="text" name="title">
    <button type="button" class="btn .btn-sm btn-success" id="search">submit</button>
</form>
user2492364
  • 6,543
  • 22
  • 77
  • 147

3 Answers3

0

Method two is better for performance reason since you limit the scope of the checking that needs to happen every time there is a button click.

The first approach is no more performant than the now deprecated live delegate, but necessary if you can't narrow the scope of the region that needs to be monitored for click events.

TGH
  • 38,769
  • 12
  • 102
  • 135
0

Case - 1

/*method 1*/
$(document).on('submit', '.login-form', function(){
    ttest = $(this).serialize();
    console.log(ttest);    
});

This is event delegation. Where you trigger it on submit of everything on the document, and check whether the target was having a class, .login-form, then do the rest.

You can read more about event delegation in jquery here.

Case - 2

/*method 2*/
$(".searchtitle").on('click',   function(){
    ttest = $(this).serialize();
    console.log(ttest);    
});

This is attaching an event to a particular DOM element. It wont trigger on all the submits on the document. But only for the particular element.

Community
  • 1
  • 1
Mithun Satheesh
  • 27,240
  • 14
  • 77
  • 101
0

The first one is called event delegation, if your .searchtitle elements added to DOM later,

  • the first one will work (new added elements have event handlers).
    $('body').on('click', 'p', function (e) {
        $(this).css('background', 'yellow');
    });
    
    $('button').on('click', function () {
        $('<p></p>').html('Hello').prependTo('body');
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    
    <p>Hello</p>
    <p>Hello</p>
    
    <button>Add Element</button>
  • but the second one won't (new added elements doesn't have any event handler).
    $('p').on('click', function (e) {
        $(this).css('background', 'yellow');
    });
    
    $('button').on('click', function () {
        $('<p></p>').html('Hello').prependTo('body');
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    
    <p>Hello</p>
    <p>Hello</p>
    
    <button>Add Element</button>
dashtinejad
  • 6,193
  • 4
  • 28
  • 44