【问题标题】:How to highlight a word in an HTML list form a string with JavaScript如何使用 JavaScript 突出显示 HTML 列表中的单词形成字符串
【发布时间】:2020-10-16 14:03:16
【问题描述】:

我有一个给定的单词(来自输入),我将使用它从对象列表中搜索并返回字符串(如果它具有给定的单词)。我已经这样做了,并且将其显示在列表中,但是当给定单词第一次出现在字符串上时,我需要用红色突出显示。

这是我目前的代码:

function consultaCompras(){
    let palabra=document.getElementById("buscarConsultas").value.trim();

    while (document.getElementById("listaResultado").hasChildNodes()){
        document.getElementById("listaResultado").removeChild(document.getElementById("listaResultado").lastChild);
    }

    let mostrarString=sistema.realizarConsulta(palabra);

    if(mostrarString.length==0){
        alert("No hay compras con la palabra ingresada.")
    }else{
        for(let j=0;j<mostrarString.length;j++){

            let nodoLi=document.createElement("LI");
            let nodoTexto=document.createTextNode(mostrarString[j]);
            nodoLi.appendChild(nodoTexto);
            document.getElementById("listaResultado").appendChild(nodoLi);
        }
    }
}

变量“mostrarString”有一个数组,其中包含给定单词的所有字符串,然后使用 for 循环我将获取所有字符串并将它们添加到列表中。

这没问题,但我不知道如何更改给定单词第一次出现在字符串上时的颜色。

【问题讨论】:

  • 创建一个可重现的示例将帮助人们进行调试。
  • 问题是任务非常大,我必须与类(其中两个)共享 HTML 和另一个 JS 文件才能使其工作。

标签: javascript html css arrays string


【解决方案1】:

所以大致如下:

for(let i = 0; i < mostrarString.length; i++) {
    //break each sentence down to its own array of words
    let splitString = mostrarString[i].split(" "); 
    let rebuiltString = '';

    for(let j = 0; j < splitString.length; j++) {
        //if the word matches palabra variable and is the first occurrence in the sentence
        if(splitString[j] === palabra && splitString.indexOf(splitString[j]) === j){
            //wrap it in a span tag
            rebuiltString += `<span style="color:red">${splitString[j]}</span>`
        } else {
            //otherwise add to new string as is
            rebuiltString += splitString[j]
        }
        //add a space except after last word
        if(i !== splitString.length - 1) {
            rebuiltString += " "
        }
    }
    const newItem = document.createElement('li');
    //set the string as the innerhtml so the span tag renders
    newItem.innerHTML = rebuiltString; 
    document.getElementById('listaResultado').append(newItem);
}

【讨论】:

    【解决方案2】:

    所以这可能需要一些调整,因为我不是 100% 了解你的变量(mostrarString 是一个单词数组吗?)但是在 for 循环中添加:

    if(mostrarString.indexOf(mostrarString[j]) === j) {
        nodoLi.setAttribute("style","color:red;")
    }
    

    【讨论】:

    • 是的,mostrarString 是一个字符串数组。我得到了您尝试做的事情,但是我需要更改与字符串中给定单词匹配的单词的颜色,而不是整个字符串。所以,我有一个字符串数组(mostrarString),它们都有给定的单词,但是现在我需要更改给定单词的颜色(并且仍然显示完整的字符串,但是给定的单词是红色的第一个它出现在字符串上的时间)。
    【解决方案3】:

    我想你可能想要这样的东西

    这是一个例子

    <body>
    <div id="banner-message">
      </div>
      <script>
        input=" beautiful"
        var mostrarString=["spanish is a beautiful language javascript is a beautiful language"," is a beautiful language javascript is c# beautiful language" ]
        function findmatch(input , str){
          mod= str.replace(input, `<span style="color:red"> ${input}</span>`)
          return   `<p> ${mod} </p>`
        }
        if(mostrarString.length==0){
                alert("No hay compras con la palabra ingresada.")
            }else{
                for(let j=0;j<mostrarString.length;j++){
                    modifiedtext=findmatch(input,mostrarString[j])
                    var nodoLi=document.createElement("div")
                     nodoLi.innerHTML=(`${modifiedtext}`);
                    document.getElementById("banner-message").appendChild(nodoLi);
                }
            }
        
          </script>
    </body>

    【讨论】:

      猜你喜欢
      • 2018-12-12
      • 2020-02-04
      • 2012-09-09
      • 2020-10-12
      • 1970-01-01
      • 1970-01-01
      • 2018-07-31
      • 2014-12-21
      • 1970-01-01
      相关资源
      最近更新 更多