Html 如何用新标签单独包装句子

Html 如何用新标签单独包装句子,html,jquery,Html,Jquery,我想用中的新标记单独包装这些句子。如何使用JQuery实现这一点?我知道我可以用$(p).contents().eq(2).wrap(“”)和$(p).contents().eq(4).wrap(“”),但这是硬编码的。我在段落中的句子数量是动态的 <!-- How do I change this --> <p> <span>1</span> This is the 1st sentence. <span>2</sp

我想用
中的新标记单独包装这些句子。如何使用JQuery实现这一点?我知道我可以用
$(p).contents().eq(2).wrap(“”)和
$(p).contents().eq(4).wrap(“”)
,但这是硬编码的。我在段落中的句子数量是动态的

<!-- How do I change this -->
<p>
  <span>1</span>
  This is the 1st sentence.
  <span>2</span>
  This is the 2nd sentence.
</p>

<!-- to become this? -->
<p>
  <span>1</span>
  <span>This is the 1st sentence.</span>
  <span>2</span>
  <span>This is the 2nd sentence.</span>
</p>


1.
这是第一句话。
2.
这是第二句话。

1. 这是第一句话。 2. 这是第二句话。


您可以通过换行符将段落的子元素吐出,然后循环检查跨度包装器是否存在

检查下面的示例

var p=document.querySelector(“p”);
var pChild=p.innerHTML.split('\n');
var pChildWrapped=pChild.map(函数(e){
返回e.indexOf(“”)!=-1?e:`${e.trim()}`;
});
console.log(pchildrapped.join('\n'));
//您可以如下更改段落内容
//p.innerHTML=pchildrapped.join('\n')

1.
这是第一句话。
2.
这是第二句话。

使用contents()并过滤非空文本节点(nodeType==3)并包装()这些节点

$('p').contents().filter(函数(){
返回this.nodeType===3&&!!this.textContent.trim();
}).wrap(“”)


1.
这是第一句话。
2.
这是第二句话。

这是否回答了您的问题?不,这是硬编码的。对不起,我的段落没有换行符。都在一条线上。为了便于阅读,我把它们拆开。无论如何,谢谢。:)