如何将 .each() 函数实现到一段代码中?

How to implement .each() function into piece of code?

我还在努力学习 JS 的基础知识。

基本上我只想从给定的 class 中删除第一个单词。像这样:

之前:

<span class="remove-word">on the beach</span>

之后:

<span class="remove-word">the beach</span>

我通过创建这段代码设法做到了:

jQuery(document).ready(
function(){
jQuery('.remove-word').text(jQuery('.remove-word').text().replace('on',''));
jQuery('.remove-word').text(jQuery('.remove-word').text().replace('at',''));
});

现在的问题是,如果我在一个页面上只有一个“.remove-word”class 实例,那么它可以正常工作,但因为我有很多实例,所以我需要将代码包装在一个 . each() 函数否则会发生这种情况:

jQuery(document).ready(
function(){
jQuery('.remove-word').text(jQuery('.remove-word').text().replace('on',''));
jQuery('.remove-word').text(jQuery('.remove-word').text().replace('at',''));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div><span class="remove-word">on the beach</span></div>

<div><span class="remove-word">at the roof</span></div>

<div><span class="remove-word">on the hill</span></div>

如何在此处实现 .each() 函数?

或者,我认为一个只删除第一个单词而不查找“on”或“at”的脚本是理想的,但我试过了,但就目前的情况而言,我的 js 知识有限,这对我来说是遥不可及的,这就是为什么我使用 .replace() 方式代替它。

谢谢。

这个呢?

jQuery('.remove-word').each(function( index ) {
    //get the index of the first space to the end of the string
    var firstWord = $(this).text().substring($(this).text().indexOf(' '), $(this).text().length);
    //set the value
    $(this).text(firstWord );  
});

您需要对根本没有文本或没有空格的 .remove-word 进行一些错误处理,但这应该是一个很好的起点

你可以做到这一点。您可以将.each添加到.remove-word class然后替换它们的内容。

$(document).ready(function() {
  $(".remove-word").each((idx,htmlSpan)=>{
    $(htmlSpan).text($(htmlSpan).text().replace('at',''));
  })
});

如果您只想删除第一个单词,那么您可以这样做。

$(document).ready(function() {
  $(".remove-word").each((idx,htmlSpan)=>{
    let text = $(htmlSpan).text(); // get text
    let splittedText = text.split(" "); // split sentence on space. returns array.
    let remainingWords = splittedText.splice(1); // get array from index 1 to last so index 0 is removed.
    $(htmlSpan).text(remainingWords.join(" ")) // .join is joining string with " " space
  })
});