我正在尝试做的事情:如标题所述,如果它是保留字,我想设置它的 CSS。
HTML
<html>
<body>
<code id="java">
public static void main(String[] args)<br>
{
<pre> System.out.println("Hello World!");</pre>
}
</code>
</body>
</html>
jQuery
$(document).ready(function()
{
// Get the text inside the code tags
var code = $("#java").text();
// Split up each word
var split = code.split(' ');
// Array of reserved words
var array = ["abstract","assert","boolean","break","byte","case",
"catch","char","class","const","continue","default",
"do","double","else","else if","enum","extends","final",
"finally","float","for","goto","if","import","implements",
"instanceof","int","interface","long","native","new","null",
"package","private","protected","public","return","short",
"static","strictfp","super","switch","synchronized","this",
"throw","throws","transient","void","volatile","while"];
// Added when text contains a reserved word
var css = {'font-weight':'bold','color':'#2400D9'}
array = jQuery.map(array, function(n,i)
{
for (int j=0; j<array.length; j++)
{
if (split[i].contains(array[j]))
split[i].css(css);
}
});
});
问题:我已经参考了几种方法的文档(在下面的参考部分),但我不太确定问题出在哪里。为了缩小问题范围,我的问题是......
- 甚至是
.split()
jQuery中的方法吗? - 我应该使用
for
循环来遍历数组中的所有单词(查看代码是否包含保留字)还是有更好的方法(例如.each()
)? - 如果我应该使用
.each()
,有人可以给我一个简单的例子吗?我不理解文档中的示例。
参考