如何在有序列表中定位数组的特定部分

时间:2016-09-05 01:03:27

标签: javascript html css

如何将姓氏定位为红色?在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);

2 个答案:

答案 0 :(得分:1)

我将名称分为2,名字和姓氏。然后我使用span元素来包含姓氏。 span有一个类,所以我然后将CSS应用于类:

&#13;
&#13;
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;
&#13;
&#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>