我仍在努力學習 JS 的基礎知識。
基本上我只想從給定的類中洗掉第一個單詞。像這樣:
之前:
<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”類的實體,這可以正常作業,但是由于我有很多我需要將代碼包裝在 .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() 方式代替。
謝謝。
uj5u.com熱心網友回復:
那這個呢?
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 進行一些錯誤處理,但這應該是一個很好的起點
uj5u.com熱心網友回復:
你可以這樣做。您可以添加.each到.remove-word類,然后替換它們的內容。
$(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
})
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/482970.html
標籤:javascript html
上一篇:特定字串或僅數字的正則運算式
下一篇:訪問陣列元素中的前一個元素
