【问题标题】:jQuery replace full name with first name within multiple instances of the same class [duplicate]jQuery在同一个类的多个实例中用名字替换全名[重复]
【发布时间】:2014-07-19 19:44:44
【问题描述】:

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

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

我怎样才能只用名字替换全名?

【问题讨论】:

  • 这是一个简单的问题,有一个简单的解决方案。快速谷歌搜索将提供您需要的任何信息。我认为这个问题需要重复关闭
  • 显然有一个愚蠢的问题,我想这就是我正在做的。我想如果我不知道该怎么做并且找不到它,我应该问。猜不到。

标签: javascript jquery


【解决方案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
});

编辑:正如我在 cmets 中所指出的,这将获得具有类标签名称的第一个元素。如果这个类有多个元素,您可能需要不同的选择器。 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);
    });
});

【讨论】:

  • 如果有几十个标签名跨度怎么办?
  • 实际上,对于我的场景,我确实需要它来处理 .label-name 的多个实例。
  • 谢谢,成功了。 @j08691
  • 不确定感谢我的原因,但不客气 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-11-15
  • 1970-01-01
  • 2013-10-26
  • 1970-01-01
  • 1970-01-01
  • 2018-06-08
  • 1970-01-01
相关资源
最近更新 更多