开发者

JQuery Append To Multiple Elements Fails

I'm trying to use jQuery's append() method to append common content to set of div's as follows:

$("#horizontal_menu").append(menu);
$("#vertical_menu").append(menu);

What I'm finding is that the content (in this case, menu) is getting appended to vertical_menu but not horizontal_menu. Does appending to one <div> preclude you from appending that con开发者_运维技巧tent to another <div>?


You can flip it around using .appendTo() like this:

menu.appendTo("#horizontal_menu, #vertical_menu");

If menu isn't a jQuery object just wrap it:

$(menu).appendTo("#horizontal_menu, #vertical_menu");

Currently what's happening is it does get appended, or more accurately moved to #horizontal_menu, then gets immediately moved again. Passing a selector or multiple elements to .appendTo() makes it clone and append to each internally.


Does appending to one preclude you from appending that content to another ?

With respect to [jQuery wrapped] DOM elements, yes. Under the hood jQuery calls appendChild, which when called multiple times with the same element simply moves it from its current position to the new position.

You can try cloning to make a copy:

var $menu = $(menu);
$("#horizontal_menu").append($menu.clone());
$("#vertical_menu").append($menu.clone());

You can pass true to clone() if you want event handlers to be copied over as well.


Another cloning twist:

        var menu = $("#menu").contents();
        menu.clone().appendTo("#ulOne");
        menu.clone().appendTo("#ulTwo");


I was experiencing a similar issue whereby I couldn't add the const removeLink via the normal .append() method. Using Nicks advice above I was able to get it working as such.

        const removeLink = $("<span class='removelink'/>").html("X").on('click', function() {
          $(this).prev().remove();
          $(this).remove();
          counter --;
        });

        $(removeLink).appendTo('.dogname-inputs, .dogage, .dogweight, .mealplan');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜