简体   繁体   English

动态添加新对象时Javascript停止

[英]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. 我试图动态添加后面带有一些JS的新“ li”对象,但是当我添加它们时,添加的“ li”中的JS不起作用。

here's the JS: JavaScript File 这是JS: JavaScript文件

and this is how i'm adding the new "li" : 这就是我添加新的“ 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". 我在控制器中调用的C#中的函数返回带有“ li”的字符串。

and just calling Boxgrid.init() does not help. 仅调用Boxgrid.init()并没有帮助。

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 每当您希望JS在动态插入的对象上运行时

When you have regular javascript on selectors everything gets binded when the document is ready. 当您在选择器上使用常规JavaScript时,文档准备就绪后,所有内容都将被绑定。 If you insert an element afterwards JS functions don't know that it exists and therefore it does not bind. 如果之后插入元素,JS函数将不知道该元素存在,因此不会绑定。

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 当您将父级用作选择器时,javascript会绑定到PARENT本身,每当您单击父级时,它将通过每个父级绑定函数并查看其是否匹配

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

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