A more efficient JavaScript code for a highlighting function?

后端 未结 4 1390
Happy的楠姐
Happy的楠姐 2021-01-19 04:19

So this is the functionality I need to clean up:

I need to create a function where viewers can click on any word in a sentence, and it will be highlighted. However,

4条回答
  •  南方客
    南方客 (楼主)
    2021-01-19 04:33

    Sorry to add to the noise... my answer is very similar to Jorgs and Roberts, and it also checks for valid answers.

    JS Fiddle is here:

    http://jsfiddle.net/M7faZ/3/

    The checkAns function uses the ID of the sentence element, to map the answer object to the selectedAnswer object.

    The HTML has carefully chosen ID and classnames:

    • Can you draw an eagle?
    • She is good in painting.

    And the JS has a map of answers.

    // get the list
    var $sentences = $('.sentence'),
        answers = {
            ans1: 'you',
            ans2: 'She'
        },
        selectedAnswers = {};
    
    function checkAns() {
        var correct;
    
        for (var i in answers) {
            correct = selectedAnswers[i] === answers[i]
    
            $('#mark-symbol-' + i).toggleClass('smile', correct);
            $('#mark-symbol-' + i).toggleClass('sad', !correct);
        }
    }
    

    If you care about people cheating, this part should be done on the server so it's not exposed to the client.

提交回复
热议问题