本文介绍了使用jQuery在特定字符串之前添加Span的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在使用jQuery的特定字符串之前添加HTML元素?例如,如果我有:

 < h4>男子篮球vs.乔治敦< / h4> 

我想这样做:

 < h4>男子篮球< span class =team> vs。乔治敦< /跨度>< / H4> 

我可以用jQuery来做到吗?我尝试过使用各种选项(:包含,prepend(),html(),pop()等等,但是它们中的任何一个都看起来没有什么不对。

解决方案



假设每个 h4 你希望包含在一个范围内,那么你应该遍历每一个,确定<$ c $的位置



html:< h4>男人的篮球与乔治城



css: .team {color:red;}


  $(h4) .each(function(){
var v ='vs。',t = $(this),prefix,suffix;
if(t.text()。indexOf(v)> -1 ){
prefix = t.text()。substr(0,t.text()。indexOf(v));
prefix + =< span class ='team'>;
后缀= t.text ().substr(t.text()的indexOf(V)。);
后缀+ =< / span>;
t.html(前缀+后缀);
}
});


Is it possible to add a HTML element before a specific string using jQuery? For example, if I have:

<h4>Men's Basketball vs. Georgetown</h4>

And I would like to make it:

<h4>Men's Basketball <span class="team">vs. Georgetown</span></h4>

Can I do that with jQuery? I have tried to use a variety of options (:contains, prepend(), html(), pop(), etc. But none of them seem to work exactly right.

解决方案

jsFiddle Demo

Assuming that for every h4 you would like the vs. and what follows wrapped in a span, then you should iterate through each one, determine the location of vs. in the string and then wrap it in a span.

html: <h4>Men's Basketball vs. Georgetown</h4>

css: .team{ color: red; }

js:

$("h4").each(function(){
 var v = 'vs.',t = $(this), prefix, suffix;
 if(t.text().indexOf(v) > -1 ){
  prefix = t.text().substr(0,t.text().indexOf(v));
  prefix += "<span class='team'>";
  suffix = t.text().substr(t.text().indexOf(v));   
  suffix += "</span>";
  t.html(prefix+suffix);
 }
});

这篇关于使用jQuery在特定字符串之前添加Span的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 02:17