Attach javascript/jquery event on dynamically created elements

白昼怎懂夜的黑 提交于 2019-12-05 11:11:49

Solution:

I am going to answer your base question "Attach javscript/jquery event on dynamically created elements".

For adding event on dynamically created elements you have to take advantage or Event Delegation, when a event trigger on an element it propagates.

So if you attach event handler on a root element( it can be body or any parent element which is present when you are attaching this event)

$("body").on("click","elementSelector", function(){

});

Now this will capture event from dynamically created elements as well.

The easiest solution is to create a function in javascript which will be called everytime when you add any control dynamically on the page and in that function you can placed the check so event will be registered only on new components. e.g.

function registerEvents()
{
    //Get all the select events from the page and register events only on those controls which are new ..
    $("select").each(function() {

        if (!$(this).hasClass("registeredEvent")) {

              $(this).addClass("registeredEvent");
              $(this).select2();
        }
    });

}

Same results can be achieved through different approaches..

Also check .live event in jquery .. it register events automatically when the new element is added with the same tag or class..

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!