Save selection text and show it later in html and javascript

后端 未结 8 930
悲哀的现实
悲哀的现实 2020-12-14 18:39

I have a difficult situation with html and javascript. My html page allows user to select text and highlight it with colors. Now I want to save the state into database to sh

8条回答
  •  醉话见心
    2020-12-14 18:55

    Since you use a plugin for text highlighting, get the highlighted words using jQuery:

    var words = $('.highlight').map(function() { return $(this).text(); });
    

    Then put them in an array

    var saved = [ ];
    for (var word in words) {
        if (-1 === saved.indexOf(word)) {
            saved.push(word);
        }
    }
    

    Finally you can save them in the database. A bad (but quick) way to do this is to save the list as comma delimited, a famous SQL antipattern:

    var wordList = saved.join(',');
    

    When you retrieve the value, you split it into words, and for each word invoke the highlight plugin.

    This will not work if any of the texts contain a comma. In that case you'd better save each word individually, which saves several other troubles in the end, rather than figuring out a separating character that's "unlikely" to pop up in a user text.

提交回复
热议问题