在Jquery中,如何将段落文本的一部分封装在span中。

时间:2022-07-25 20:34:31

How do I wrap the innerhtml found after a span in a paragraph inside a span. Better explained by example:

如何将span后的innerhtml封装在span中的一个段落中。更好的解释为例子:

<p>foo <span>bar</span> baz</p>

I want to get:

我想要:

<p>foo <span>bar</span><span> baz</span></p>

baz is possible marked up as well (ie can contain links etc).

baz也可以标记(比如可以包含链接等)。

Ive tried

我试过

$(p span).first().contents().filter(function() {
    return this.nodeType == 3;
}).text();

But only gives me the inner span text of first span...

但是只给了我第一个span的内span文本……

3 个解决方案

#1


7  

DEMO

演示

var span = $('p > span:first')[0];
var target = [];
while(span.nextSibling) {
    target.push(span.nextSibling);
    span = span.nextSibling;
}
$(target).wrapAll('<span />');

#2


2  

This might work

这可能工作

$('<span>').insertAfter('span')
$('</span>').appendTo('p')

You'll want to be more specific with your targetting of course.

当然,你需要对你的目标做更具体的说明。

#3


0  

Thanks for your help @Sahil Muthoo, @Saul and @puppybeard, unfortunately I had trouble getting your suggested answers working, so at last I came up with this which, allthough looks a bit overdone, works for my case.

谢谢你的帮助@Sahil Muthoo, @Saul和@puppybeard,不幸的是,我无法让你的建议答案发挥作用,所以最后我想到了这个方法,尽管看起来有点过头了,但对我的情况来说还是很有用。

See live demo over at jsFiddle.

请参阅jsFiddle的live demo。

var p = $('p').clone();
p.children('span').first().replaceWith('[split]');
var aParts = p.html().split('[split]');
var newP = $('<p>').text(aParts[0]).append($('p').children('span').first());
if (aParts.length > 1) {
    newP.append($('<span>').html(aParts[1]));
}       
$('p').replaceWith(newP);

Suggestion for cleaning up the above mess would be appriciated.

对清理上述混乱局面的建议将被提出。

#1


7  

DEMO

演示

var span = $('p > span:first')[0];
var target = [];
while(span.nextSibling) {
    target.push(span.nextSibling);
    span = span.nextSibling;
}
$(target).wrapAll('<span />');

#2


2  

This might work

这可能工作

$('<span>').insertAfter('span')
$('</span>').appendTo('p')

You'll want to be more specific with your targetting of course.

当然,你需要对你的目标做更具体的说明。

#3


0  

Thanks for your help @Sahil Muthoo, @Saul and @puppybeard, unfortunately I had trouble getting your suggested answers working, so at last I came up with this which, allthough looks a bit overdone, works for my case.

谢谢你的帮助@Sahil Muthoo, @Saul和@puppybeard,不幸的是,我无法让你的建议答案发挥作用,所以最后我想到了这个方法,尽管看起来有点过头了,但对我的情况来说还是很有用。

See live demo over at jsFiddle.

请参阅jsFiddle的live demo。

var p = $('p').clone();
p.children('span').first().replaceWith('[split]');
var aParts = p.html().split('[split]');
var newP = $('<p>').text(aParts[0]).append($('p').children('span').first());
if (aParts.length > 1) {
    newP.append($('<span>').html(aParts[1]));
}       
$('p').replaceWith(newP);

Suggestion for cleaning up the above mess would be appriciated.

对清理上述混乱局面的建议将被提出。