我正在嘗試做什麼:如標題所述,如果它是保留字,我想設置一個單詞的CSS。 當它包含保留字時設置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);
}
});
});
問題:我已提及了幾種方法的文件(在下面的參考文獻部分),但我不太確定問題的存在。要縮小這個問題了,我的問題(S)將...
- 是
.split()
jQuery的甚至的方法? - 我是否應該使用
for
循環遍歷數組中的所有單詞(以查看代碼是否包含保留字)還是有更好的方法(例如.each()
)? - 如果我應該使用
.each()
,有人請給我一個簡單的例子嗎?我不明白文檔中的例子。
參考
jQuery是JavaScript和使用JavaScript方法,所有的時間。檢查這個帖子,它可能會有所幫助 - http://stackoverflow.com/questions/784012/javascript-equivalent-of-phps-in-array – 2012-03-16 21:19:25
['.split()'](http://www.w3schools .com/jsref/jsref_split.asp)是JavaScript中的一個字符串方法。所以它也是jQuery中的字符串方法;)。 – Zeta 2012-03-16 21:19:50
btw,$ .each()執行比本地JS for循環慢一點(http://jsperf.com/jquery-vs-lowdash-loops/4),但使用起來更方便。如果沒有很多元素,我更喜歡.each()。隨着更多的元素性能差異開始顯示,然後我通常使用通常的循環。 – 2013-11-16 03:55:40