简体   繁体   English

使用 jQuery & java 突出显示文档中的单词列表

[英]Highlight list of words in the document using jQuery & java

I am using know the following code to highlight specific word in the document我正在使用知道以下代码来突出显示文档中的特定单词

<script> 
$(document).ready(function(){
   $('h1').highlight('word1');
      });
</script>

it works fine just to highlight one word !!仅突出一个词就可以正常工作!

but I have an arrylist in my program which is written in java ArrayList wordsList;但我的程序中有一个 arrylist,它是用 java ArrayList wordsList 编写的;

I do not know how to make it I wrote the following我不知道怎么做我写了以下

<script>
         $(document).ready(function(){
          for (int y=0;y<wordslist.size();y++) 
          { 
         $('h1').highlight(wordslist.get(y));
          }
     });
</script>

it does not work, this does not highlight the words in the list它不起作用,这不会突出显示列表中的单词

You need to use <% %> for your Java code:您需要为您的 Java 代码使用<% %>

<script>
      $(document).ready(function(){
         <% for (int y=0;y<wordslist.size();y++) 
          { %> 
         $('h1').highlight('<%= wordslist.get(y) %>');
        <%  } %>
     });
</script>

wordsList is a Java variable. wordsList 是一个 Java 变量。 It's usable only at server-side.它仅在服务器端可用。 You need to iterate it at client-side, where JavaScript is executed.您需要在执行 JavaScript 的客户端对其进行迭代。 You thus need to transform the Java variable into JavaScript code:因此,您需要将 Java 变量转换为 JavaScript 代码:

<script>
  $(document).ready(function() { 
     var javaScriptWordList = [
         <c:forEach var="word" items="${wordList}">'${word}', </c:forEach> // JSP : server-side
     ];  
     for (var i = 0; i < javaScriptWordList.length; i++) {
         $('h1').highlight(javaScriptWordList[i]);
     }
 });
</script>

Once this JSP is executed, if the Java wordList contains "hello", "world", the generated HTML will look like this:一旦这个 JSP 被执行,如果 Java wordList 包含“hello”,“world”,则生成的 HTML 将如下所示:

<script>
  $(document).ready(function() {
     var javaScriptWordList = [
         'hello', 'world',
     ];
     for (var i = 0; i < javaScriptWordList.length; i++) {
         $('h1').highlight(javaScriptWordList[i]);
     } 
 });
</script>

Note however that you should certainly escape the words inside the list, in case they contain characters which would make the JavaScript code invalid (for example, if one of the word is O'Reilly).但是请注意,您当然应该转义列表中的单词,以防它们包含会使 JavaScript 代码无效的字符(例如,如果单词之一是 O'Reilly)。 Look at commons-lang StringEscapeUtils.escapeJavaScript查看 commons-lang StringEscapeUtils.escapeJavaScript

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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