简体   繁体   English

如何将 jQuery Function 应用于新创建的 DOM 元素?

[英]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.似乎每次我使用 AJAX 创建按钮元素时,在$(document).ready上创建的 Javascript 都不起作用,这是有道理的,因为它是在文档准备好之后创建的。 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.这是有问题的 function,对于所有带有.additem的按钮,当页面加载时,它工作得很好,但是当使用.additem创建新按钮时,它根本不起作用。

So I believe the javascript isn't being called on the new element.所以我相信 javascript 不会在新元素上被调用。 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.我试过$().click但由于某种原因它不适用于新创建的按钮。

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.我也尝试过$().change()但它会创建同一脚本的多个副本。 So that when I click the button it does it +1 times everytime I click the button.因此,当我单击该按钮时,每次单击该按钮时它都会执行 +1 次。 Ending up creating like 5 of the same item everytime I click .additem .每次我点击.additem时,最终都会创建 5 个相同的项目。

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在 jQuery 中,如果您希望事件处理程序触发事件处理程序绑定添加的元素'.additem' ,您需要使用“委托”事件处理程序,请参阅https://api.jquery.com/on/#direct -和委托事件

$(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).在这里你需要记住将该处理程序附加到所有目标元素的元素(我在这个例子中使用了document )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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