简体   繁体   中英

How can I apply a jQuery Function to a newly created DOM Element?

I'm creating a menu and submenu items all async.

It seems like everytime I create a button Element using AJAX, the Javascript created on $(document).ready isn't working on it, which makes sense because it was created after the document ready. But what do I use to catch newly created elements?

This is the function in question, for all the buttons with .additem on it when the page is loaded, it works perfectly, but when the new button is created with .additem it doesn't work at all.

So I believe the javascript isn't being called on the new element. I've done several tests and I'm confident that's the case, but of course I could be wrong.

$('document').ready(function(){


$('.additem').click( function(e) {
  
    e.preventDefault();
    console.log('test')
    const category_id = $(this).attr('id');
    const url = `/add_item/${category_id}/`;
    const name = $(`.newitemname${category_id}`).val();
    const price = $(`.newitemprice${category_id}`).val();
    const description = $(`.newitemdescription${category_id}`).val();

    $.ajax({
      type: 'POST',
      url: url,
      data: {
        'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val(),
        'name':name,
        'price':price,
        'description':description,
      },
      success:function(response) {
        console.log('success', response);
        $(`.itemlist${response['category_id']}`).append($(`
          <li class="row"> 
            <div class="fw-normal mb-0 col-8"> ${response['item_name']} </div> 
            <div class="col-3 text-muted pl-5" align="right">$ ${response['item_price']}</div>
            <p class="fw-lighter lh-sm" style="font-size: 12px;"> ${response['item_description']} </p> 
          </li>
        `));
      },
      error:function(response){
        console.log('error', response)
      },
    });

})

I've tried $().click but it doesn't apply to the newly created buttons for some reason.

It works on the elements that are already on the page just fine though.

I've also tried $().change() but it creates multiple copies of the same script. So that when I click the button it does it +1 times everytime I click the button. Ending up creating like 5 of the same item everytime I click .additem .

In jQuery, if you want event handlers to fire on elements '.additem' that are added after the event handler is bound you need to use 'delegated' event handlers, see https://api.jquery.com/on/#direct-and-delegated-events

$(document).on('click', '.additem', function(e) { } );

Here you need to remember to attach that handler to a parent element of all target elements (I used document in this example).

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