[英]jQuery Prepend Open Tag Append Closing Tag
Firstly, I am familiar with . 首先,我很熟悉。
wrapAll()
and that is not what I need. wrapAll()
,这不是我需要的。 I have some markup that I am not able to change and I need to wrap everything in a <li>
. 我有一些标记,我无法更改,我需要在
<li>
包装所有内容。
Here is what I am trying to do: 这是我想要做的:
$('nav[role="breadcrumb"] ul a').wrap('<li></li>'); $('nav[role="breadcrumb"] ul li:last').after('<li>'); $('nav[role="breadcrumb"] ul').append('</li>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <nav role="breadcrumb"> <ul class="clearfix"> <a href="http://eggaday.armystage.com/">Home</a> <a href="http://eggaday.armystage.com/health-care-professionals/">Health Care Professionals</a> Healthy Choices Cholesterol Kits </ul> </nav>
The problem is that jQuery closes each of these <li>
tags. 问题是jQuery会关闭每个
<li>
标签。 Here is the original markup: 这是原始标记:
<nav role="breadcrumb"> <ul class="clearfix"> <a href="http://eggaday.armystage.com/">Home</a> <a href="http://eggaday.armystage.com/health-care-professionals/">Health Care Professionals</a> Healthy Choices Cholesterol Kits </ul> </nav>
As you can see, I have some loose text at the bottom of this <ul>
and I am trying to get it wrapped in an <li>
. 正如您所看到的,我在
<ul>
的底部有一些松散的文本,我试图将其包含在<li>
。
.contents()
will get all the children, including the text nodes .contents()
将获取所有子节点,包括文本节点
$('nav[role="breadcrumb"] ul').contents().filter(function() {
return $.trim($(this).text())!=="";
}).wrap('<li/>');
EDIT: Added the filter method to get rid of the whitespace text nodes 编辑:添加了过滤方法来摆脱空白文本节点
jQuery only works with complete elements, you can't append just a closing or opening tag. jQuery仅适用于完整元素,您不能只附加一个结束标记或开始标记。
If the ul doesn't have any other list items, you could simply use wrapInner 如果ul没有任何其他列表项,您可以简单地使用wrapInner
$('nav[role="breadcrumb"] ul').wrapInner("<li />");
If it does contain LI's, the easiest way would be to detach them, wrap inner, then append them. 如果它确实包含LI,最简单的方法是分离它们,包裹内部,然后附加它们。
var $lis = $('nav[role="breadcrumb"] ul > li').detach();
$('nav[role="breadcrumb"] ul').wrapInner("<li />").prepend($lis);
Try creating your <li> first and then append your selector to it: 首先尝试创建<li>,然后将选择器附加到它:
var $li = $('<li>').append('nav[role="breadcrumb"] ul a');
Then use $li to replace or append anywhere you like. 然后使用$ li替换或追加您喜欢的任何地方。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.