gpt4 book ai didi

jquery - 如何包装和排除特定标签

转载 作者:搜寻专家 更新时间:2023-10-31 08:09:16 25 4
gpt4 key购买 nike

我想使用 jquery 的函数包装,或者可能与其他解决方案一起使用,但我需要包装 div 的内容,并排除特定标记,如 <sup> <i> <strong> .我用下面的例子解释

我有这个:

<div>
my test without tag<sup>1</sup> and the end of sentence.
<p>text with tag p <br />
break line
</p>
Second sentence without <i>tag</i> and the end.
<div>

我想要这个:

<div>
<p>my test without tag<sup>1</sup> and the end of sentence.</p>
<p>text with tag p <br />
break line
</p>
<p>Second sentence without <i>tag</i> and the end.<p>
<div>

所以我用 JQuery 在 JS 中执行此操作,

$( "div" )
.contents()
.filter(function(){
return this.nodeType !== 1;
})
.wrap( "<p></p>" );

但是这个 JS 是这样做的:

<div>
<p>my test without tag</p>
<sup>1</sup>
<p> and the end of sentence.</p>
<p>text with tag p <br>
break line
</p>
<p>Second sentence without </p><i>tag</i><p> and the end.</p>
</div>

我创建了这个 jsFiddle

最佳答案

function wrapElements(elements){
$(elements).wrapAll('<p></p>');
}

$('div').each(function(){
var elementsToWrap=[];
var contents=$(this).contents();
contents.each(function(){
if($(this).text().trim()){
if(this.nodeName!='P'){
elementsToWrap.push(this);
}else{
wrapElements(elementsToWrap)
elementsToWrap=[];
}
}
});
if(elementsToWrap.length)
wrapElements(elementsToWrap);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
my test without tag<sup>1</sup> and the end of sentence.
<p>text with tag p <br />
break line
</p>
Second sentence without <i>tag</i> and the end.
</div>

看看上面的代码。它产生正确的输出。但我相信它可以进一步改进。

注意:我已经使用 P 标签来比较标签是否是段落标签,如果不是,那么我会持有它直到我得到下一个 P 标签并且我将所有在 P 标签中。 (可能还有很多其他逻辑可以做到这一点)

关于jquery - 如何包装和排除特定标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50948482/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com