简体   繁体   English

使用jQuery将子动态添加到ul

[英]Add a child li dynamicaly to ul with jquery

I want to add a custum li to an ol with jquery event, this is my code 我想用jQuery事件向ol添加一个custum li ,这是我的代码

success: function(data) {
            if (data != ''){
                $ulSub = $("#firstList");
                                $("#Pushtype_destinationList").val(crit1);
                $.each(data.dataa, function (i,item) {
           $str="";

                    for(var key in item){ if(key != 'id'){$str+= item[key]} }
                    $ulSub.append( '<li class="ui-widget-content " id="'+item.id +'" >' +$str+'</li>');

                });
            }
        }

and my code in html given as follow 和我的HTML代码如下

 <ol class="selected" id="firstList">
                <li class="ui-widget-content ">text 1</li>
                <li class="ui-widget-content ">text 2</li>

            </ol>

and the function jquery that add an element li from the first ol to the second ol is as 将第一个ol的元素li添加到第二个ol的函数jquery为

    jQuery('ol#firstList li').click(function() {

       $(this).toggleClass('selected');

      $('#result').html($('#firstList .selected').clone())

   });

until now every thing work great, but when I clic on a new element add dynamically by using this function 到现在为止,一切工作都很好,但是当我选择一个新元素时,可以使用此函数动态添加

 ( `for(var key in item){ if(key != 'id'){$str+= item[key]} }
                            $ulSub.append( '<li class="ui-widget-content " id="'+item.id +'" >' +$str+'</li>');

                        });)   

this element cannot be added to the second <ol id="result> 此元素不能添加到第二个<ol id="result>

在此处输入图片说明

as you see here, when the element text1 and text2 are added when i clic on them, but the other element which are added dynamically not 如您在此处看到的,当我单击它们时,当添加元素text1和text2时,但是动态添加的其他元素没有

any help please 任何帮助请

It happens because you only assign your event handler to items already existing in the DOM by the time your event handler assignment code runs. 之所以会发生这种情况,是因为在事件处理程序分配代码运行时,您仅将事件处理程序分配给DOM中已经存在的项目。

Try: 尝试:

jQuery(document).on('click', 'ol#firstList li', function() {
     $(this).toggleClass('selected');
     $('#result').html($('#firstList .selected').clone())
});

Look jQuery documentation for '.on' for further details. 有关更多详细信息,请在jQuery文档中查找“ .on”。

clear html before each loop like 像每个循环之前清除html

$ulSub.html('');

PUT fellow code PUT同伴代码

success: function(data) {
            if (data != ''){
                $ulSub = $("#firstList");
                $("#Pushtype_destinationList").val(crit1);
                $ulSub.html('');
                $.each(data.dataa, function (i,item) {
                $str="";
                for(var key in item){ if(key != 'id'){$str+= item[key]} }
                    $ulSub.append( '<li class="ui-widget-content " id="'+item.id +'" >' +$str+'</li>');

                });
            }
        }

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

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