当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Can't wrap a jQuery object with a selector

问题描述:

<div id="foo"></div>

<script type="text/javascript">

$('<p>Hi Mom</p>').wrap('#foo');

</script>

Demo: http://jsfiddle.net/6uWP8/

My intention is to place the newly-created HTML inside of #foo (and keep a reference to that newly-created HTML for further calls). The documentation for $.fn.wrap() seems to tell me that I should be able to pass a selector as the argument. But the end result is no change to the document.

What is wrap() really doing? And how do I instead inject new HTML into the page while retaining a reference to it for chained calls? (Hint: I'm saying that $('#foo').html(…) is not a solution.)

网友答案:

I think what you are looking for is .appendTo(), it will return the newly created element

var $el = $('<p>Hi Mom</p>').appendTo('#foo');

Demo: Fiddle

网友答案:

You are wrapping the $('<p>Hi Mom</p>') in the div #foo, since the element being wrapped is not in the dom you're not going to see it. What happens is a copy of #foo is made and wrapped over the fragment,

$('<p>Hi Mom</p>').wrap('#foo').parent().prop('id')

will give you foo.
I think you were expecting the <p>Hi Mom</p> to be placed inside the #foo which would be an insert and not a wrap.

http://jsfiddle.net/6uWP8/1/

网友答案:

Musa is correct about the reason why wrap is not acting as you are expecting. This is in response to Phrogz comment saying

Can you explain please what wrap() is doing instead of what I expected it to, and what it's used for?

Here is a simple example of using wrap that helps illustrate what it's doing. I added a click event that wraps #foo with an h1 tag:

 $('.change-size').click(function(e) {
    e.preventDefault();
    $('#foo').wrap('<h1></h1>');
});

When you click on the "Click Here" link, you can see the text size change because of the new h1. Makes it a little clearer that the new tag (h1) is being placed outsize of what is in the selector (#foo). See the jsfiddle:

http://jsfiddle.net/gS3K8/1/

Hope that helps!

分享给朋友:
您可能感兴趣的文章:
随机阅读: