Rob*_*Rob 7 html javascript css jquery reserved-words
我想做的事情:正如标题中所述,我想设置一个单词的CSS,如果它是一个保留字.
<html>
<body>
<code id="java">
public static void main(String[] args)<br>
{
<pre> System.out.println("Hello World!");</pre>
}
</code>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
$(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);
}
});
});
Run Code Online (Sandbox Code Playgroud)
.split()jQuery中甚至一个方法是什么?for循环来遍历数组中的所有单词(以查看代码是否包含保留字)或者是否有更好的方法(例如.each())?.each(),有人可以给我一个简单的例子吗?我不明白文档中的示例.如果我理解正确,您可以使用标签来实现您想要的目的$.inArray并包装保留字span。看我的演示
编辑:以下来自 jQuery $.inArray 文档。
$.inArray( value, array [, fromIndex] )-value要搜索的值。
array要搜索的数组。
fromIndex开始搜索的数组的索引。默认值为 0,将搜索整个数组。
CSS
.code {
font-weight: bold;
color: #2400D9;
}
Run Code Online (Sandbox Code Playgroud)
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(' '));
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1209 次 |
| 最近记录: |