简体   繁体   中英

Javascript stops when add new objects dynamically

i'm trying to add new "li" objects that have some JS behind dynamically, but when i add them the JS in the added "li" does not work.

here's the JS: JavaScript File

and this is how i'm adding the new "li" :

$(document).ready(function () {
    $('#search-bar').keyup(function (event) {
        if (event.keyCode == 13) {

            addNew();

        }
    });

    function addNew() {
        var city = $('#search-bar').val();
        $.ajax({
            url: '@Url.Action("getWeatherSearch", "Index")',
            data: { city: city },
            async: false,
            complete: function (resp) {
                $("#rb-grid").prepend(resp.responseText);
            }
        });
    } });

The function in C# that i'm calling in the controller returns a string with the "li".

and just calling Boxgrid.init() does not help.

Use

$('#parentofli').on('click', 'li', function(e) {
   $(this). whatever you want to do on the li
});

Whenever you want JS to run on dynamically inserted objects

When you have regular javascript on selectors everything gets binded when the document is ready. If you insert an element afterwards JS functions don't know that it exists and therefore it does not bind.

when you use the parent as the selector then the javascript binds to the PARENT itself and whenever you click in the parent it will go through each parent binded function and see if it matches

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