jQuery在同一个类的多个实例中用名字替换全名

时间:2014-07-19 19:44:45

标签: javascript jquery

我在类.label-name中有一个全名,它有多个实例。

<span class="label-name">Joe Demo</span>
<span class="label-name">Jane Demo</span>
<span class="label-name">Lisa Demo</span>

如何只用第一个名字替换全名?

1 个答案:

答案 0 :(得分:1)

您可以获取文本,按空格拆分,然后取第一个元素。

例如:

$( document ).ready(function() {
    var fullName = $(".label-name").first().text(); //This will get the text from the first element with the class label-name
    var nameArray = fullName.split(" "); //Split the text by spaces into an array
    var firstName = nameArray[0]; //Take the first element of the array 
    $(".label-name").first().text(firstName); //Set the text of the first element with the class label-name to the first name
});
编辑:正如我在评论中指出的那样,这将获得带有class label-name的第一个元素。如果此类有多个元素,则可能需要使用不同的选择器。 jQuery选择器记录在http://api.jquery.com/category/selectors/。如果您发布完整的HTML源代码并让我知道您想要哪个元素,我将提供进一步的建议。

编辑2:如果您需要选择并替换具有相同类的多个元素,则可以从代码中删除.first()选择器并使用循环编辑结果。例如:

$( document ).ready(function() {
    var fullNameObjects = $(".label-name");
    $.each(fullNameObjects, function () {
         var nameArray = this.split(" ");
         var firstName = nameArray[0];
         this.text(firstName);
    });
});