0

我需要在我的页面上找到一个句子并用 span 标签(带有一个类)包装它。

这是我的页面:

<body>
<h1>Home Page</h1>
<p>Welcome to the homepage of the site. Enjoy your stay</p>
</body>

使用 Javascript,我想将 P 内容转换为:

<p><span class="mySpan">Welcome to the homepage</span> of the site. Enjoy your stay</p>
4

2 回答 2

0

这是你需要做的:

  1. 使用 .innerHtml 或 jQuery.html() 读取 html。
  2. 解析数据
  3. 使用 .innerHtml 或 jQuery.html() 写回数据

您可以使用 RegEx 和其他各种方式进行解析。这是一个简单的示例。

var html = $("p").html();
html = "<span>" + html;
html = html.replace("homepage","homepage</span>");
$("p").html(html);

这是一个有效的 jsFiddle:http: //jsfiddle.net/QjDvR/2/

于 2013-06-03T15:14:21.457 回答
0

如果您不想使用 jquery,请尝试以下操作:

<script>  
  P = document.getElementsByTagName('p');
  search = 'Welcome to the homepage';
  s = P[0].innerHTML.replace(search,'<span class="mySpan">' + search +'</span>');
  P[0].innerHTML =s;
</script> <!-- always locate script at the end of the body -->
</body>  

但是,为了增强它,您应该考虑将 ID 属性包含到元素中,并使用方法 document.getElementById('the_id') 选择此元素。

于 2013-06-03T15:24:08.853 回答