Cloning a bootstrap element with an event listener

后端 未结 4 1540
既然无缘
既然无缘 2021-01-11 13:37

I\'m trying to clone a bootstrap element that has data-toggle behavior provided by bootstrap:

HTML

&
4条回答
  •  太阳男子
    2021-01-11 14:31

    So far your code is ok, just remove true from clone() it's not needed.

    UPDATED

    This Boolean value indicates whether event handlers should be copied along with the elements. The default value is to the false . So, when we were calling the .clone() method without passing any Boolean value, it was just copying the elements but not the event handlers attached to it. But, when we pass the value true , it copies both the elements and any event handlers attached to it.

    But Bootstrap is handling the event handlers for dynamic objects so you don't need to true in clone.

    LIKE

    If you're handling events for dynamic objects using this way

    $(".btn").click(.....); 
    // This button was dynamically created and you want a click event for it, 
    // but it wont work because at the time of event binding this button wasn't exist at all.
    

    BUT

    You need to handle events for dynamic objects using event delegation technique.

     $(document).on("click",".btn",function(){ .... });
    

    This will work, because the event handler is bound to an element higher up the DOM tree (in this case, the document) and will be executed when an event reaches that element having originated on an element matching the selector, And that's what Bootstrap does for dynamic objects, also you do the same if needed for dynamic objects. Hers is JSFiddle for this.

    Also you need to wrap the whole collapsible part in a div for cloning.

    Note: Using .clone() has the side-effect of producing elements with duplicate id attributes, which are supposed to be unique. Where possible, it is recommended to avoid cloning elements with this attribute or using class attributes as identifiers instead.

    So, you need to update data-target and div id attribute after cloning, so that newly created button targets the newly created collapse panel

    I am using jQuery for it.

    Here is the code Snippet

    $(function(){
      var target = "collapsible_obj_";
      var i = 1;
      
      $("#button").click(function(){
        $(".parent_colapse:last").clone().insertAfter(".parent_colapse:last");        
        $(".parent_colapse:last > button").attr("data-target", "#"+target+i);
        $(".parent_colapse:last .collapse").attr("id", target+i);
        i++;
      });
      
      $(document).on("click",".button",function(){
         alert();
      });
    });
    
    
    
    
    

    About your question you haven't shown your full script that's the reason we are unable to find the bug. LIKE we don't know objectContainer nor collapsibleObjCounter what that is ?

提交回复
热议问题