如何使用jQuery将部分文本包装成跨度?

时间:2022-11-29 10:55:20

Here is what I am trying to do

这就是我要做的

Fox<span>Rox</span>

before that

在那之前

FoxRox

How do I wrap spans around Rox?

如何围绕Rox展开?

2 个解决方案

#1


6  

This will search you whole DOM and replace each Rox with <span>Rox</span>:

这将搜索整个DOM,并将每个Rox替换为Rox:

$(':contains("Rox")').html(function(index, oldHTML) {
    return oldHTML.replace(/(Rox)/g, '<span>$&</span>');
});​

Live DEMO

现场演示

#2


5  

In this case, you could use the JavaScript replace() method:

在这种情况下,可以使用JavaScript replace()方法:

'FoxRox'.replace(/(Rox)/, '<span>$1</span>');

To replace this all through the document, you could try the following:

要在整个文件中替换这一切,您可以尝试以下方法:

$(":contains('Rox')").html(function(i,o){
  return o.replace(/(Rox)/g, '<span>$1</span>');
});​

Note, if your term is not "Rox", you'll need to change it in the above script.

注意,如果您的术语不是“Rox”,您需要在上面的脚本中更改它。

#1


6  

This will search you whole DOM and replace each Rox with <span>Rox</span>:

这将搜索整个DOM,并将每个Rox替换为Rox:

$(':contains("Rox")').html(function(index, oldHTML) {
    return oldHTML.replace(/(Rox)/g, '<span>$&</span>');
});​

Live DEMO

现场演示

#2


5  

In this case, you could use the JavaScript replace() method:

在这种情况下,可以使用JavaScript replace()方法:

'FoxRox'.replace(/(Rox)/, '<span>$1</span>');

To replace this all through the document, you could try the following:

要在整个文件中替换这一切,您可以尝试以下方法:

$(":contains('Rox')").html(function(i,o){
  return o.replace(/(Rox)/g, '<span>$1</span>');
});​

Note, if your term is not "Rox", you'll need to change it in the above script.

注意,如果您的术语不是“Rox”,您需要在上面的脚本中更改它。