7

我正在尝试做的事情:如标题所述,如果它是保留字,我想设置它的 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);
        }
    });
});


问题:我已经参考了几种方法的文档(在下面的参考部分),但我不太确定问题出在哪里。为了缩小问题范围,我的问题是......

  1. 甚至是.split()jQuery中的方法吗?
  2. 我应该使用for循环来遍历数组中的所有单词(查看代码是否包含保留字)还是有更好的方法(例如.each())?
  3. 如果我应该使用.each(),有人可以给我一个简单的例子吗?我不理解文档中的示例。


参考

4

2 回答 2

4

如果我理解正确,您可以使用标签来实现您想要$.inArray的效果。span看我的DEMO

编辑:以下来自 jQuery $.inArray 文档。

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

value 要搜索的值。

数组要搜索的数组。

fromIndex 开始搜索的数组的索引。默认值为 0,它将搜索整个数组。

..阅读更多..

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(' '));
});
于 2012-03-16T21:29:36.910 回答
2

几个月前我问过自己这个问题,经过大量搜索后,我发现了这个问题:

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

我将其添加到以下 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();
            }
        })
    }
}

它没有办法“撤消”关键字包装,但它适合我的需要。

If you need an example how to implement this I'd be happy to make one if you provide some text I can test it on....

于 2012-03-16T21:36:03.380 回答