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 ;
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:
<script>
$(document).ready(function(){
<% for (int y=0;y<wordslist.size();y++)
{ %>
$('h1').highlight('<%= wordslist.get(y) %>');
<% } %>
});
</script>
wordsList is a Java variable. It's usable only at server-side. You need to iterate it at client-side, where JavaScript is executed. You thus need to transform the Java variable into JavaScript code :
<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:
<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). Look at commons-lang StringEscapeUtils.escapeJavaScript
精彩评论