标签: JavaScript

使用jQuery Autocomplete(自动完成)插件

jQuery的Autocomplete(自动完成、自动填充)插件有不少,但比较下来我感觉,还是bassistance.de的比较强大,我们就来写一些代码感受一下。

最简单的Autocomplete(自动完成)代码片段

1
2
3
4
5
6
7
8
9
<script type="text/javascript">
var websites = [
	"Google","NetEase", "Sohu", "Sina", "Sogou", "Baidu", "Tencent", 
	"Taobao", "Tom", "Yahoo", "JavaEye", "Csdn", "Alipay"
];
$().ready(function() {
	$("#website").autocomplete(websites);	
});
</script>
1
2
3
4
5
6
<p>
<label>Web Site:</label>
<input type="text" id="website" />
<input type="button" id="getvalue" value="Get Value" />
</p>
<div id="content"></div>

我们可以看到效果

jQuery Autocomplete Plugin

这么几行代码就完成了自动完成功能,真实太强了,不过bassistance.de的jQuery Autocomplete插件还有更丰富的功能,它的文档在http://docs.jquery.com/Plugins/Autocomplete,在API Documentation里,我们要仔细的研究一下autocomplete( url or data, [options] )方法。

autocomplete方法有两个参数,第一个用来填写URL地址或是数据,jQuery Autocomplete插件是支持Ajax方式调用数据,所以可以填写调用的地址,另外可以直接填写数据,格式为JavaScript数组,如我们的例子,autocomplete的另外一个参数 [options]是一个可选项,我们在例子中就没有写,但这个参数里面却有很多可配置的参数,我们还是先修改上面的例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
$().ready(function() {
	$("#website").autocomplete(websites,{
		minChars: 0,
		max: 5,
		autoFill: true,
		mustMatch: true,
		matchContains: true,
		scrollHeight: 220,
		formatItem: function(data, i, total) {
			return "<I>"+data[0]+"</I>";
		},
		formatMatch: function(data, i, total) {
			return data[0];
		},
		formatResult: function(data) {
			return data[0];
		}
	});
});

在options项我们增加了好几个参数

minChars表示在自动完成激活之前填入的最小字符,这里我们设置为0,在我们双击文本框,不输入字符的时候,就会把数据显示出来,效果如下

jquery-autocomplete-21

max表示列表里的条目数,我们设置了5,所以显示5条,也如上图

autoFill表示自动填充,就是在文本框中自动填充符合条件的项目,看下图,在我们输入“g”的时候,文本框里填充了“google”

jQuery Autocomplete Plugin

mustMatch表示必须匹配条目,也就是在文本框里输入的内容,必须是data参数里的数据,如果不匹配,文本框就被清空

matchContains表示包含匹配,就是data参数里的数据,是否只要包含文本框里的数据就显示,比如在上面的图中,我们输入了“g”,由于“Sogou”中也包含一个“g”,所以会显示出来,如果将matchContains设为fasle,则“Sogou”就不会显示

scrollHeight不用多解释,看文档就知道。

后面3个参数formatItem、formatMatch、formatResult非常有用,formatItem作用在于可以格式化列表中的条目,比如我们加了“I”,让列表里的字显示出了斜体,formatMatch是配合formatItem使用,作用在于,由于使用了formatItem,所以条目中的内容有所改变,而我们要匹配的是原始的数据,所以用formatMatch做一个调整,使之匹配原始数据,formatResult是定义最终返回的数据,比如我们还是要返回原始数据,而不是formatItem过的数据。

[options]里还有很多有用的参数,大家可以看它的文档。

jQuery Autocomplete插件里还有两个重要的方法,一个是result( handler ),一个是search( ),比如用户在选定了某个条目时需要触发一些别的方法时,着两个方法就可以起作用了,我们再修改以上的例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
$().ready(function() {
 
	function findValueCallback(event, data, formatted) {
		$("#content").html("<strong>"+(!data ? "No match!" : "Selected: " + formatted)+"</strong>");
	}
 
	$("#website").autocomplete(websites,{
		minChars: 0,
		max: 5,
		autoFill: true,
		mustMatch: true,
		matchContains: true,
		scrollHeight: 220,
		formatItem: function(data, i, total) {
			return "<I>"+data[0]+"</I>";
		},
		formatMatch: function(data, i, total) {
			return data[0];
		},
		formatResult: function(data) {
			return data[0];
		}
	});
	$("#website").result(findValueCallback);
	$("#getvalue").click(function() {$("#website").search()});
});

看看是什么效果,会在content div的地方显示出我们选择的内容。

jQuery Autocomplete插件所带的例子还是很好的,大家可以仔细研究一下它的例子,更加灵活的运用jQuery Autocomplete插件。

用jQuery Form Plugin实现Ajax无刷新的文件上传

在我以前的意识里,觉得用JavaScript或Ajax提交文件表单似乎是一件麻烦的事情,也没有太仔细的研究,后来看jQuery的时候,发现了jQuery Form Plugin这个插件,它方便的实现了Ajax方式的表单提交,例子里也包括了文件表单的提交,那我也来试一下吧,还是用Kohana(最近专注于这个,而且PHP开发要快多了,要是用Struts,要费好多功夫)。

要Kohana支持上传,先要配置一些upload的参数,把system\config\upload.php拷贝到application/config下,里面的参数做好设置,具体参考Kohana的文档吧,之后创建一个Controller

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Myupload_Controller extends Top_Controller {
 
	public function index() {
		$view = new View ("upload");		
		$view->msg = "Upload File";
 
		$view->render ( TRUE );
	}
 
	public function upload() {		
		$filename = upload::save('myfile');
		echo $filename;
 
		exit ();
	}
 
}

Top_Controller为我自己创建的类,也继承自Kohana的Controller,之后创建upload.php的view文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<html>
<head>
<title><?php echo $msg;?></title>
<script type="text/javascript" src="<?=url::base()?>js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="<?=url::base()?>js/jquery.form.js"></script>
<script type="text/javascript"> 
        // wait for the DOM to be loaded 
        $(document).ready(function() { 
        	var options = { 
        		target:        '#fileinfo'   // target element(s) to be updated with server response         
        	};
 
        	$('#myForm').submit(function() { 
        		$(this).ajaxSubmit(options);
        		return false; 
        	});
 
        }); 
</script>
</head>
 
<body>
<h2><?php echo $msg;?></h2>
<form id="myForm" action="<?=url::base()?>myupload/upload" method="post"
	enctype="multipart/form-data">
	<input name="myfile" type="file" />
	<input type="submit" value="Submit Comment" />
</form>
<div id="fileinfo"></div>
</body>
</html>

在这里我们用jQuery Form Plugin来提交表单,之后将信显示在“fileinfo”这个div里,去试试效果吧。

http://malsup.com/jquery/form/里有详细的API和例子,同时http://malsup.com/jquery/里也有其他的一些不错的jQuery的插件。

从JavaEye上找的Google翻译JavaScript脚本

在Blog或新闻发布的时候,我们希望URL是一段有意义的字串,例如我Blog里的《Linux下切分Tomcat的catalina.out日志文件》文章链接是https://i.laoer.com/2009/02/18/rotating-catalina-out-in-tomcat-using-cronolog/,这样有利于SEO(搜索引擎优化),对于我们母语为中文的小虾,有时候要翻译标题还是有点头疼的,还好有了Google翻译,让翻译的事情变得简单了一点,但对于开发者,怎么使用户也方便的翻译,特别是在写Blog的时候就能把标题翻译好,还要动点脑筋,我看到JavaEye里发布新闻的地方有个“让Google帮助生成永久链接”的功能挺好的,看了一下他们的源码,得到以下这段,顺别也解释一下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<script type="text/javascript" src="http://www.google.com/jsapi"></script> //载入Google的jsapi
 
<script type="text/javascript">  
 
  function slugify(str) { //这个方法应该是将字符转为小写,并把一些特殊字符转为"-"
    return str.toLowerCase().replace(/[^a-z0-9-_]+/g, '-').replace(/^-|-$/g, '');
  }
 
  google.load("language", "1"); //载入Google的language Ajax库
 
  function translate_title() { //这里就是翻译文章标题了,里面的方法需要jQuery支持,之前要引入jQuery的包,这里就省略了
    if($F("news_title").blank()) {
      alert("请先填写标题");
      return;
    }
    $("news_slug_url").value = "正在翻译中...";
    google.language.translate($F("news_title"), "zh", "en", function(result) {
      if (!result.error) {
        $("news_slug_url").value = slugify(result.translation);
      }
    });
  }  
</script>

这里有个地方要说一下,Google的Ajax库API还是挺好的,可以load几种Ajax的库,另外Google的Web 工具包也可以看看。