我可能做错了什么,但我尝试了各种方法,但似乎无法包装jQuery对象的集合。以下代码只输出未包装的HTML链接。有什么想法吗?
$.each(sitemapSections, function(i) {
var $sitemapSection = $(sitemapSections[i]);
var $primary = $sitemapSection.find('a[data-level="1"]').wrap('<h3></h3>');
$dropdownSections[i].html($primary);
});编辑-以下是标记(已清理):
<li id="product-solutions"><a href="#link" class="alpha grid-6">Products & Solutions</a>
<div id="ps-dropdown" class="dropdown-menu grid-20">
<div class="ps-dropdown-section">
</div><!-- .ps-dropdown-section -->
<div class="ps-dropdown-section">
</div><!-- .ps-dropdown-section -->
<div class="ps-dropdown-section">
</div><!-- .ps-dropdown-section -->
</div><!-- .dropdown-menu -->
</li>更新-我知道了!提到parent()的注释就是我所遗漏的。下面是最终的代码:
$.each(sitemapSections, function(i) {
var $sitemapSection = $(sitemapSections[i]);
var $primary = $sitemapSection.find('a[data-level="1"]').wrap('<h3></h3>').parent();
$dropdownSections[i].html($primary);
});发布于 2012-09-21 11:30:09
jquery .wrap()将内部元素返回给您,因此看起来没有任何变化。
$("<div>").wrap('<span>')
===>
[<div></div>]这看起来好像没起作用。
但是:
$("<div>").wrap('<span>').parent()
===>
[<span><div></div></span>]它确实起作用了。
发布于 2010-08-26 04:40:01
看起来您打算使用jQuery的html方法在倒数第二行添加html -除非$dropdownSections是一个数组,每个元素都是一个jQuery对象。我想你可能想要这个:
$.each(sitemapSections, function(i) {
var $sitemapSection = $(sitemapSections[i]);
var $primary = $sitemapSection.find('[data-level="1"]').wrap('<h3></h3>');
$dropdownSections.eq(i).html($primary.parent().html());
});或者更多地写成另一种方式:
$.each(sitemapSections, function(i) {
$dropdownSections.eq(i).html(
$(sitemapSections[i])
.find('[data-level="1"]')
.wrap('<h3></h3>')
.parent()
.html()
);
});如果$dropdownSections是一个在每个元素中都有一个jQuery对象的数组:
$.each(sitemapSections, function(i) {
$dropdownSections[i].html(
$(sitemapSections[i])
.find('[data-level="1"]')
.wrap('<h3></h3>')
.parent()
.html()
);
});发布于 2010-08-26 04:28:36
你需要一个字符串来传递给.html(),我认为你是在追求这个:
$dropdownSections[i].empty().append($primary.parent());这将获取.parent() (因为您刚刚将其包装在其中)并将内容设置为该the。
https://stackoverflow.com/questions/3569922
复制相似问题