在我试图解释我的意思之前,这里有一个我想要实现的目标的例子。
现在的情况:
<ul>
<li>My name: Sietse</li>
<li>Country: The Netherlands</li>
</ul>
我希望它是:
<ul>
<li><strong>My name:</strong> Sietse</li>
<li><strong>Country:</strong> The Netherlands</li>
</ul>
我的网站上有很多现有的内容都像第一个例子一样被标记,但有没有一种方法可以动态选择和设置文本样式,直到LI中(可能包括)冒号,如第二个例子所示?
请注意,我是jQuery或任何Javascript的绝对初学者。
您可以像一样使用.html()和字符串替换()
$('ul li').html(function (i, html) {
return html.replace(/(.*?:)/, '<strong>$1</strong>')
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul>
<li>My name: Sietse</li>
<li>Country: The Netherlands</li>
</ul>
尝试以下
$(function() {
$("ul li").each(function() {
if ($(this).text().indexOf(':') > -1) {
$(this).html('<strong>' + $(this).html().split(':').join(':</strong>'));
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul>
<li>My name: Sietse</li>
<li>Country: The Netherlands</li>
</ul>