简体   繁体   中英

javascript not changing the text color

I have a function that I want to change the font color of the user entered string if it is equal to a certain word located in an array.. So far when I step through it it says that it changes the font color but it actually never updates it to the screen and I don't know why. Here is what I have so far

function getLastWord() {
    var input = document.getElementById("my_text");
    //var input = document.getElementById(textArea.value);
    //var lineIn = document.getElementById(my_text).innerHTML;
    var inputValue = input.value;
    var lastWordTyped
    var changeColorOfWord;

    if (input == null) {
        input == " ";
    }

    //lastWordTyped = input.substr(input.trim().lastIndexOf(" ") + 1);
    lastWordTyped = inputValue.substr(inputValue.trim().lastIndexOf(" ") + 1);

    if (input != null) {

        for (var i = 0; i < reservedKeyWords.length; i++) {
            if (reservedKeyWords[i] === lastWordTyped) {
                lastWordTyped = lastWordTyped.fontcolor("blue");
                my_text.replace(inputValue, lastWordTyped);
            } else {

            }


        }
    }
}

string.fontcolor is legacy, and should not be used even though I could see it as a viable option in this case

Essentially, what you are doing is adding font tags around the word:

var txt = 'hello world';
txt = txt.fontcolor('blue');
//txt = '<font color="blue">hello world</font>';

You do not show what you do with the result, but if you actually put it in an HTML element it should work, even though instead of using fontcolor, I'd rather use element.style.color . This would require slightly more work though:

var ele = document.querySelector('#my_text');
ele.style.color = 'blue';
ele.innerHTML = lastWordTyped;

If you still want to go with the .fontcolor method, you could just keep what you have in the question and add

input.innerHTML = my_text;

I see two issues with the code thus far.

  1. You are using 'fontcolor("blue")' parameter on the lastWordTyped. The proper syntax to change color is element.style.color="#CCC" .

  2. You will need to wrap the last typed word in a span so you can target it and apply the color to just that word.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM