A more efficient JavaScript code for a highlighting function?

后端 未结 4 1357
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:32

    This could maybe work if the amount of content is limited else you might experience some lag onload.

    Start out by gathering all the elements that need this ability into an array. Split each sentence using " " as the variable into another temporary array. Step through temp array adding a span tag around each word with a new class. Then return the new string with span tags to the corresponding element. This can be down with 2 for loops. Last bind both hover and onclick to each new tag by using another for loop. Sorry no code, I'm watching tosh lol, but if you make a jsfiddle I will write it for you.

    Like I said this shouldn't be done with a lot of sentences at one time. You could always stagger sentences if you have multiple sections.

    Hope this helps explain how I would do it. Good luck let me know what happens!

    0 讨论(0)
  • 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:

    <ul class='sentences'>
      <li class='sentence' id='ans1'>Can you draw an eagle?</li>
      <li class='sentence' id='ans2'>She is good in painting.</li>
    </ul>
    
    <div id='mark-symbol-ans1'></div>
    <div id='mark-symbol-ans2'></div>
    

    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.

    0 讨论(0)
  • 2021-01-19 04:39

    A similar solution to Jorg's, with some variations. I've done the wrapping with split() and join() instead of regex. I also tend to put my jQuery chains on separate lines for visual clarity.

    <html>
    <head>
        <script type="text/javascript" src="./jquery.min.js"></script>
        <script type="text/javascript"> 
    
        $( document ).ready( function() {
            var p = $( "p", "#myDiv" );
            $.each( p, function( i, obj ){
                $( obj )
                    .attr( "class", "highlightable" );
                obj.innerHTML = "<span>" + obj.innerHTML.split(" ").join( "</span> <span>" ) + "</span>";
            });
    
            $( ".highlightable span", "#myDiv" )
                .on( "click", function(){
                    $( "span", $( this ).parent() )
                        .css( "background-color", "");
                    $( this )
                        .css( "background-color", "#ffff45" );
                });
        });
    </script>
    
    </head>
    <body>
    
    <div id="myDiv">
        <p>Here is a sentence.</p>
        <p>Here is another sentence.</p>
        <p>Here is yet another sentence.</p>
    
    </div>
    </body>
    </html>
    
    0 讨论(0)
  • 2021-01-19 04:47

    As per @DrewGoldsBerry's answer, with some example code. Here's a working fiddle of the code below: http://jsfiddle.net/E3D6T/1/

    Set up your HTML with a class to indicate which lines should have the highlight functionality.

    <p class="highlight">Each word will be wrapped in a span.</p>
    <p class="highlight">A second paragraph here.</p>
    

    In your JS, split the p elements into words wrapped in span tags, which can then be bound to a click function:

    // wrap words in spans
    $('p.highlight').each(function () {
        var $this = $(this);
        $this.html($this.text().replace(/\b(\w+)\b/g, "<span>$1</span>"));
    });
    
    // bind to each span
    $('p.highlight span').click(function () {
        $(this).parent().find('span').css('background-color', '');
        $(this).css('background-color', '#ffff66');
    });
    

    edit:

    http://jsfiddle.net/jorgthuijls/E3D6T/16/

    I added all the answer checking to the click function itself. Should be fairly straight forward.

    0 讨论(0)
提交回复
热议问题