简体   繁体   English

如何使用jQuery将页面元素与动态生成的元素包装在一起?

[英]How do I wrap a page element with a dynamically generated element using jQuery?

I have the following code 我有以下代码

var input = $('#el_id');
wrapper = $(document.createElement('div'));
wrapper.addClass('small');
wrapper.css('width',200);
input.wrap(wrapper);

alert(input.children().length)

I get 0 for the children length. 孩子的长度我得到0。 What I want is: 我想要的是:

<div class="small" style="width: 200px;">
     <input type="text" id="el_id" />
</div>

But I want the small div to be dynamically generated. 但我希望小div动态生成。 Any idea why this isn't working? 知道为什么这行不通吗?

UPDATE UPDATE

It turns out my issue lies on another line of code. 事实证明,我的问题出在另一行代码上。 I want to assign the wrapper to a variable after I wrap and: 我想在包装后将包装器分配给变量:

block = input.wrap("<div class='"+container_class+"' style='width: "+wrap_width+"px;'></div>");

does not work. 不起作用。 It returns the input which makes sense. 它返回有意义的输入。 But how can I return the wrapper? 但是我如何退还包装纸?

Thanks! 谢谢!

I believe you are doing it right. 我相信您做对了。

You just need to save the results of the wrap function to a variable: 您只需要将wrap函数的结果保存到一个变量中:

Edit: Updated the code to get parent(): 编辑:更新代码以获取parent():

var wrapped = input.wrap(wrapper).parent();
alert(wrapped.children().length);

From the documentation , it appears that wrap() only accepts a DOM element or a string. 文档看来,wrap()仅接受DOM元素或字符串。 You are passing it a jQuery object, which may not work. 您正在向它传递一个jQuery对象,该对象可能不起作用。 I'd try this: 我会尝试这样的:

$('#el_id').wrap('<div class="small" style="width: 200px;"></div>');

Simple. 简单。 You are trying to wrap with a jquery object and not a dom object which is what the wrap() function expects. 您正在尝试使用jquery对象而不是wrap()函数期望的dom对象进行包装。

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

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