A more efficient JavaScript code for a highlighting function?

后端 未结 4 1387
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: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.

    Each word will be wrapped in a span.

    A second paragraph here.

    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, "$1"));
    });
    
    // 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.

提交回复
热议问题