当前位置: 动力学知识库 > 问答 > 编程问答 >

jquery - javascript highlight word on base of index sent to function

问题描述:

I want to highlight the specific word index passed by function, initially function added on a button click.

The problem is when i reassign 'document.getElementById('inputText').innerHTML = filterText;'

it re-renders the page(Because there is iframe video ) and there is an iframe and another thing which are conflicting.

function makeALlIndex() {

defaultText = document.getElementById('inputText').innerHTML;

}

function changeColor(index, word) {

myText = defaultText;

var filterText = myText.substr(0, index) + '<span class="highlightClass">' + word + '</span>' + myText.substr(index + word.length);

document.getElementById('inputText').innerHTML = filterText;

}

Html

<body onload="makeALlIndex()">

<div id="inputText">

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor.

<button onclick="changeColor(0,'')">click me</button>

</div>

</body>

网友答案:

try to change your method to

function changeColor(index, word) {
   myText = defaultText;
   var filterText = myText.substring(0, index).split( word ).join( '<span  class="highlightClass">' + word + '</span>' ) +  myText.substr(index + word.length);
   document.getElementById('inputText').innerHTML = filterText;
}
网友答案:

@Aliraza -

I think following solution will work for you

function changeColor(index, word) {
    myText = defaultText;
    var filterText = '',newText ='',myTextArray =[];
    if( myText.indexOf(word)!=-1){
        myTextArray = myText.split(word);
        for(i=0; i<= myTextArray.length-1;i++){  
           if(i==index){
               newText = myTextArray[i] + '<span  class="highlightClass">' + word + '</span>';
            }else {
               newText =  myTextArray[i];
            }
            filterText += newText;
       }    
        document.getElementById('inputText').innerHTML = filterText;
    }
}    

It is based on the URL you have provided. Still there are lots of things you may need to change in it.

分享给朋友:
您可能感兴趣的文章:
随机阅读: