簡體   English   中英

如何在特定索引處的 div 內的文本中添加 div 或跨度子字符串?

[英]How to add div or span around substrings in text inside a div at specific indices?

我有一個包含字符串的 div。 例如:

<div id='original'>A red chair that is on the left of another chair next to the door</div>

我在數據庫中存儲了一些用戶選擇的子字符串,其中包含開始和結束索引。 例如:

phrase: chair, start: 43, end: 48
phrase: the door, start: 58, end: 66

現在,我想在“原始”div 中圍繞上述兩個短語添加一個 span 或一個 div,以便我可以突出顯示這些短語。

預期結果:

<div id='original'>A red chair that is on the left of another <div style="display:inline; color:#ed3833; cursor:pointer;">chair</div> next to <div style="display:inline; color:#ed3833; cursor:pointer;">the door</div></div>

對於一個短語,我可以使用開始和結束索引在其周圍插入 div,但對於后續插入,它顯然會失敗,因為索引現在已更改,因為在第一個短語周圍添加了 div。 你能幫我解決這個問題嗎?

我不知道它是否有幫助,但為了在第一個短語周圍添加 div,我使用以下邏輯:

str = $('#original').text()
var preStr = str.substring(0, startIdx);
var newStr = `<div style="display:inline; color:#ed3833; cursor:pointer;">${phrase}</div>`
var postStr = str.substring(endIdx, str.length);
result = preStr+newStr+postStr;

如果您需要更清楚的說明,請告訴我,我會嘗試更好地解釋一下。

您可以為索引形成 arrays 並這樣做:

 var str = $('#original').html(); var startInd = [43, 58]; var lastInd = [48, 66]; var count = startInd.length; for (let i = 0; i < count; i++) { let pre = str.substring(0, startInd[i]); let post = str.substring(lastInd[i], str.length); let phrase = str.substring(startInd[i], lastInd[i]); let nextPhrase; if (i < count - 1) { nextPhrase = str.substring(startInd[i + 1], lastInd[i + 1]); } str = pre + `<div style='display:inline; color:#ed3833; cursor:pointer;'>${phrase}</div>` + post; if (i < count - 1) { startInd[i + 1] = str.indexOf(nextPhrase, startInd[i + 1]) - 1; lastInd[i + 1] = startInd[i + 1] + nextPhrase.length; } } $('#original').html(str);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id='original'>A red chair that is on the left of another chair next to the door</div>

使用數據庫中的索引對您很重要嗎? 那這個呢?

result = $('#original')
  .text()
  .split(phrase)
  .join(`<div ...>${phrase}</div>`);

更好的方法是盡可能減少包裝元素,因此我建議使用 css 作為樣式。

此外,還有我們可以使用的本機 javascript 正則表達式,例如,我構建了一個小包裝器 function 作為包裝結果的助手,我也使用純 JS 而不是 jQuery 是必需的

 var el = document.getElementById('original') // target element var ht = el.innerHTML // inner html // helper wrapper function function wrapper( match ){ return '<span class="wrap">' + match + '</span>' } ht = ht.replace( /chair/g, wrapper ); ht = ht.replace( /the door/g, wrapper ); el.innerHTML = ht // write results in div console.log( ht )
 .wrap{ display: inline; color:#ed3833; cursor:pointer }
 <div id='original'>A red chair that is on the left of another chair next to the door</div>

我試了一下,也許你會發現這種方法很有用:我將字符串拆分為單詞並計算單詞長度,以便獲得當前的 position,其中將進行替換。 然后將操作放在單個元素上 - 因此全局順序/位置不會改變。 這只是一個想法,也許你可以在你的項目中使用它

    let input = 'A red chair that is on the left of another chair next to the door';
let phrases ={
    'chair' : {start: 43, end: 48},
    'the door': {start: 58, end: 66}
};
let words = input.split(' ');
let position = 0;
for (word of words) {
    position += word.length + 1 // add one extra for blank after a word;
    if (phrases.chair.start === position || phrases["the door"].start === position + 1) {
        word = "<div class='start highlight'>" + word;
    }
    if (phrases.chair.end === position || phrases["the door"].end === position) {
        word = word + "</div>";
    }
    console.log(word+" : " + position);
}

你可以這樣做:

 str= $('#original').text(); str = str.replace(/(chair(?= next to)|the door)/g, '<div style="display:inline; color:#ed3833; cursor:pointer;">$&</div>'); $('#result').html(str)
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id='original'>A red chair that is on the left of another chair next to the door</div> <p id='result'></p>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM