2012-03-16 25 views
7

我正在嘗試做什麼:如標題所述,如果它是保留字,我想設置一個單詞的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)將...

  1. .split() jQuery的甚至的方法?
  2. 我是否應該使用for循環遍歷數組中的所有單詞(以查看代碼是否包含保留字)還是有更好的方法(例如.each())?
  3. 如果我應該使用.each(),有人請給我一個簡單的例子嗎?我不明白文檔中的例子。


參考

+0

jQuery是JavaScript和使用JavaScript方法,所有的時間。檢查這個帖子,它可能會有所幫助 - http://stackoverflow.com/questions/784012/javascript-equivalent-of-phps-in-array – 2012-03-16 21:19:25

+0

['.split()'](http://www.w3schools .com/jsref/jsref_split.asp)是JavaScript中的一個字符串方法。所以它也是jQuery中的字符串方法;)。 – Zeta 2012-03-16 21:19:50

+1

btw,$ .each()執行比本地JS for循環慢一點(http://jsperf.com/jquery-vs-lowdash-loops/4),但使用起來更方便。如果沒有很多元素,我更喜歡.each()。隨着更多的元素性能差異開始顯示,然後我通常使用通常的循環。 – 2013-11-16 03:55:40

回答

4

如果我理解正確的話,你可以達到你想要使用什麼並用span標記包裝保留字。看我的DEMO

編輯:下面是從jQuery $ .inArray文檔。

$.inArray(value, array [, fromIndex]) -

valueThe值來搜索。

arrayAn通過其中進行搜索的數組。

fromIndex開始搜索的數組索引。 默認爲0,它將搜索整個數組。

..read more..

CSS

.code { 
    font-weight: bold; 
    color: #2400D9; 
} 

JS

$(document).ready(function() { 
    // Get the text inside the code tags 
    var code = $("#java").html(); 

    // 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"]; 

    for (var j = 0; j < split.length; j++) { 
     if ($.inArray(split[j], array) > 0) { 
      split[j] = '<span class="code">' + split[j] + '</span>'; 
     } 
    } 

    $("#java").html(split.join(' ')); 
}); 
+0

酷!你能解釋一下'$ .inArray(split [j],array)'嗎?主要是'$ .inArray'部分。 – Rob 2012-03-16 21:36:59

+0

@MikeDtrick查看我的編輯。你可以在jQuery文檔中清楚地閱讀更多。 – 2012-03-16 21:41:02

+0

好的,謝謝你的幫助。 – Rob 2012-03-16 21:52:45

2

我在幾個月前問自己這個問題,很多搜索,我發現這個後:

http://forum.jquery.com/topic/wrapping-specific-words-inside-span-elements#14737000001028912

我addapted分爲以下jQuery插件:

$.fn.applyKeyword = function(opt, selector) { 
    var numOfKeys = opt.keys.length; 

    if (typeof selector == 'undefined') { 
     selector = ":visible:not(:input):not(label):not(select)"; 
    } 

    for (var i = 0; i < numOfKeys; i++) { 
     if (opt.keys[i].partials) { 
      var re = new RegExp("(" + opt.keys[i].keyword + ")", 'ig'); 
     } else { 
      var re = new RegExp("(\\b" + opt.keys[i].keyword + "\\b)", 'ig'); 
     } 
     $(selector, this).contents().filter(function() { 
      return this.nodeType != 1; 
     }).each(function() { 
      var output = $(this).text().replace(re, opt.keys[i].prefix + "$1" + opt.keys[i].suffix); 
      if (output != $(this).text()) { 
       $(this).wrap("<p></p>").parent('p').html(output).contents().unwrap(); 
      } 
     }) 
    } 
} 

它沒有辦法「撤消」關鍵字包裝,但它適合我的需要。

如果你需要一個例子如何實現這一點,我很樂意做一個,如果你提供一些文字,我可以測試它....

+0

也可以通過使用正則表達式來捕獲字符串的部分匹配;如果你期望很多關鍵字/文本,這可能會有點沉重。它使用您使用它的元素作爲範圍來限制要檢查的元素。 – sg3s 2012-03-16 21:38:36

+0

我必須承認這很複雜(我在一個月前開始使用jQuery)。我很高興你提到了這個插件,因爲我已經跟着幾篇關於如何設置插件的教程,但我不知道如何「編譯」一個插件(如果這是有道理的話)。你把你的插件保存爲'.js'文件,並將它在標籤的'id'或'class'中調用? – Rob 2012-03-16 21:41:09

+0

一個插件基本上只是一個添加到jQuery對象的'屬性';它恰好是一個函數,所以它可以使用大括號()...這只是基本的JS;但要了解更多關於如何編寫插件的信息,請查看官方教程的鏈接(http://docs.jquery.com/Plugins/Authoring) – sg3s 2012-03-16 21:44:06

相關問題