使用 wrap() 后尝试 append() 时出现奇怪的 jquery 错误奇怪、错误、wrap、append

2023-09-08 08:44:43 作者:看你远走i

Using jQuery, I

Created a container

一篇学会Java8新特性

Wrapped an element with it

Selected the container by passing an object to its jQuery selector and tried to add an element to the container

Why doesn't element append()?

Look at this example here: jsfiddle.net/Tngh4

    var container = document.createElement("div");
    //Wrapping some random element with the container
    $("#randomElem").wrap(container);

    var elem = document.createElement("div");
    //Selecting element this way and using append results in a strange bug
    $(container).append(elem);

解决方案

.wrap wraps the element with a copy of the passed in element, not the passed in element itself.

A copy of this structure will be wrapped around each of the elements in the set of matched elements. This method returns the original set of elements for chaining purposes.

http://api.jquery.com/wrap

Here's your fiddle to use an alternative to .wrap http://jsfiddle.net/Tngh4/1/