[英]How to extract text from header tags, wrap in <li> and append to list, using jQuery
I'm trying to write a jQuery function to take the visible h3 tags' text and append them to a side menu.我正在尝试编写一个 jQuery 函数来获取可见的 h3 标签文本并将它们附加到侧菜单。 I've got the text appearing in the menu correctly, but I cannot strip, then wrap them in the tags I want.我已将文本正确显示在菜单中,但我无法剥离,然后将它们包裹在我想要的标签中。
I have included the code below, can anyone see why the wrapping is not working?我已经包含了下面的代码,谁能看出为什么包装不起作用?
function populateRightMenu() {
// empty existing menu right-menu-list
$('#right-menu-list').empty();
// get list of h3
var items = $('h3:visible');
// inject into menu
$(items).clone().unwrap('h3').wrap('<li></li>').appendTo('#right-menu-list');
}
.wrap()
doesn't return the newly wrapped parent items, it returns the existing items, so using .clone().wrap().append()
you're appending the clone, not the outer wrap. .wrap()
不返回新包装的父项,它返回现有项,因此使用.clone().wrap().append()
附加克隆,而不是外包装。
You can fix this by selecting the new wrapper:您可以通过选择新包装器来解决此问题:
var items = $('h3:visible');
items.clone().wrap('<li></li>').closest("li").appendTo('#right-menu-list');
alternatively, wrap the items after appending them或者,在附加项目后包装项目
items.clone().appendTo('#right-menu-list').wrap('<li></li>');
$('#right-menu-list').empty(); var items = $('#source h3'); items.clone().wrap('<li></li>').closest("li").appendTo('#right-menu-list'); $('#right-menu-list2').empty(); var items = $('#source h3'); items.clone().appendTo('#right-menu-list2').wrap('<li></li>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="source"> <h3>1</h3> <h3>2</h3> <h3>3</h3> </div> <hr/> <ul id="right-menu-list"></ul> <hr/> <ul id="right-menu-list2"></ul>
While the question is primarily about wrapp
ing with li
, there's also the question about unwrapping the h3
.虽然问题主要是关于wrapp
与荷兰国际集团li
,有也即将展开的问题h3
。 Because .unwrap()
unwraps the parents, not the items themselves.因为.unwrap()
解开父项,而不是项本身。 So you effectively want $("h3").children().unwrap("h3")
- but .children()
doesn't select text nodes - so if your h3
s are like <h3>text</h3>
then this won't work (there's no HTML in the question, so this may be ok, or you may be ok adding eg a span
in the h3
s. The easiest method here is to extract the content directly, but this won't clone any events - so it depends on how the h3
is built所以你实际上想要$("h3").children().unwrap("h3")
- 但是.children()
不选择文本节点- 所以如果你的h3
像<h3>text</h3>
那么这行不通(问题中没有 HTML,所以这可能没问题,或者您可以在h3
s 中添加例如span
。这里最简单的方法是直接提取内容,但这不会克隆任何事件 - 所以这取决于h3
的构建方式
$("#right-menu-list").append(items.map(function(i,e) { return "<li>" + $(e).html() + "</li>" }).toArray())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.