我需要将每个单词的每个首字母从特定的css类“eachword”换行到“span”html标记 - 使用javascript。 同时我有很好的工作脚本,除了一个问题,脚本转换特殊字符,如“&”成html格式。 所以,这就是我现在所拥有的:
在应用脚本之前:
<a class="eachword" href="#">Models & Brands</a>
脚本:
<script type="text/javascript">
window.onload = function()
{
var elements = document.getElementsByClassName("eachword");
for( var i=0; i<elements.length; i++)
{
elements[i].innerHTML = elements[i].innerHTML.replace(/\b([a-z])([a-z]+)?\b/gim, "<span class='firstletter'>$1</span>$2");
}
}
</script>
结果:
<a class="eachword" href="#"><span class="firstletter">Models &<span class="firstletter">a</span>mp; <span class="firstletter">Brands</span></a>
我需要这个结果:
<a class="eachword" href="#"><span class="firstletter">Models <span class="firstletter">& </span><span class="firstletter">Brands</span></a>
在“head”标签中,我还包含了jQuery 1.7.2。
所以,问题是,代码出了什么问题,我在哪里弄错了?感谢您的关注,希望对您有所帮助!
答案 0 :(得分:3)
在香草JS中,我想要快一点:
var a = document.getElementsByTagName("a");
for (i = 0; i < a.length; i++) {
var words = a[i].innerHTML.split(" ");
for (j = 0; j < words.length; j++) {
if(words[j][0] != "&") {
words[j] = "<span class='firstletter'>" + words[j][0] + "</span>" + words[j].substring(1);
}
}
a[i].innerHTML=words.join(" ");
}
更现代的方式:
var anchors = Array.from(document.getElementsByTagName("a"));
anchors.forEach(a => {
a.innerHTML =
a.textContent
.split(' ')
.map(word => {
if (word[0] != '&') {
return `<span class="firstletter">${word[0]}</span>${word.substring(1)}`;
} else {
return word;
}
})
.join(' ');
});
答案 1 :(得分:0)
这似乎对我有用,虽然可能有点笨拙
$(document).ready(function()
{
// For each of the eachword class
$("a.eachword").each(function()
{
// Get the string (html) and split it by " " (like PHP's explode)
var self = $(this);
var theText = self.html();
var theTextArray = theText.split(" ");
// Cycle them
for (var i = 0; i < theTextArray.length; i++)
{
// Get this particular word and split it into individual letters
var thisWord = theTextArray[i];
var thisWordArray = thisWord.split("");
// Wrap the first letter if it is not a HTML char code
if (thisWordArray[0] != "&")
{
thisWordArray[0] = "<span class='firstletter'>"+thisWordArray[0]+"</span>";
}
// Stitch the letters back up
theTextArray[i] = thisWordArray.join("");
}
// Join the original string back up
var result = theTextArray.join(" ");
self.html( result );
});
});