如何将姓氏定位为红色?在HTML中,我有一个名为elements
的ID,并且CSS中的ID相同,以使姓氏变为红色。我试图做各种各样的事情,但我发现没有成功。
var names = ["Jane Doe", "Jose Munez", "John Williams"];
var splitNames = names.sort().reverse();
function anything(str1) {
for (i = 0; i < str1.length; i++) {
str1[i] = str1[i].split(",").join(" ");
return str1;
}
}
console.log(anything(splitNames));
//getLastName : takes argument 'str', splits the string passed in after there's a space and retrieves all characters after the split (that's what the 1 means)
function getLastName(str) {
return str.split(' ')[1];
}
function orderedList(listItem) {
for (var i = 0; i < listItem.length; i++) {
var l = document.createElement('li');
l.innerHTML = listItem[i];
document.getElementById('elements').appendChild(l);
console.log(getLastName(listItem[i]));
var list = "";
}
}
orderedList(splitNames);
答案 0 :(得分:1)
我将名称分为2,名字和姓氏。然后我使用span元素来包含姓氏。 span有一个类,所以我然后将CSS应用于类:
var names = ["Jane Doe", "Jose Munez", "John Williams"];
var splitNames = names.sort().reverse();
function anything(str1) {
for (i = 0; i < str1.length; i++) {
str1[i] = str1[i].split(",").join(" ");
return str1;
}
}
console.log(anything(splitNames));
//getLastName : takes argument 'str', splits the string passed in after there's a space and retrieves all characters after the split (that's what the 1 means)
function getLastName(str) {
return str.split(' ')[1];
}
//New function just for convenience
function getFirstName(str) {
return str.split(' ')[0];
}
function orderedList(listItem) {
for (var i = 0; i < listItem.length; i++) {
var l = document.createElement('li');
//Notice how the span class is used to enclose the last name
l.innerHTML = getFirstName(listItem[i]) + " <span class=" + 'last-name' + ">" + getLastName(listItem[i]) + "</span>";
document.getElementById('elements').appendChild(l);
console.log(getLastName(listItem[i]));
var list = "";
}
}
orderedList(splitNames);
&#13;
.last-name {
color: red;
}
&#13;
<ul id="elements">
</ul>
&#13;
我操纵了li
的innerHTML以包含类last-name
的范围。然后我将color: red
应用于所有last-name
s。
答案 1 :(得分:0)
这是你想要的吗?
<style>
span.red-name {
color : red;
}
</style>
<ul id="elements">
</ul>
<script>
var names = ["Jane Doe", "Jose Munez", "John Williams"];
var splitNames = names.sort().reverse();
function orderedList(listItem) {
for (var i = 0; i < listItem.length; i++) {
var l = document.createElement('li');
var flname = listItem[i].split(' ');
l.innerHTML = flname[0] + ' <span class="red-name">'+flname[1] + '</span>';
document.getElementById('elements').appendChild(l);
}
}
orderedList(splitNames);
</script>