著名的 MooTools 插件之一是 Harald Kirschner 的 AutoCompleter 插件。 AutoCompleter 接受用户输入的术语并搜索匹配项——这显然对用户有帮助。以下是如何充分利用 Harald 的出色插件。
XHTML
Single Search
<input type="text" name="search" id="search" /> <br /><br /><br /><br /> <h2>Multi-Search</h2> <textarea name="search2" id="search2" ></textarea>
我们需要做的就是提供文本区域或输入元素——AutoCompleter 会完成剩下的工作。
CSS
#search,#search2 { border:1px solid #ccc; padding:6px; width:400px; background:#fff; }
ul.autocompleter-choices { position:absolute; width:339px; padding:0; list-style:none; z-index:50; background:#3b5998; border:1px solid #3b5998; top:0; }
ul.autocompleter-choices li { margin:0; list-style:none; padding:0px 10px; cursor:pointer; font-weight:normal; white-space:nowrap; color:#fff; font-size:11px; }
ul.autocompleter-choices li:hover { background:#eceff5; color:#3b5998; }
.search-working { background:url(/wp-content/themes/walshbook/images/indicator_blue_small.gif) 200px 7px no-repeat; }
我们可以根据需要为所有元素设置样式。
MooTools JavaScript
window.addEvent('domready', function() {
new Autocompleter.Request.JSON('search', 'get-terms.php', {
'postVar': 'search',
minLength: 3,
maxChoices: 10,
autoSubmit: false,
cache: true,
delay: 300,
onRequest: function() {
$('search').setStyles({
'background-image':'url(indicator_blue_small.gif)',
'background-position':'350px 7px',
'background-repeat':'no-repeat'
});
},
onComplete: function() {
$('search').setStyle('background','');
}
});
new Autocompleter.Request.JSON('search2', 'get-terms.php', {
'postVar': 'search',
minLength: 3,
maxChoices: 10,
autoSubmit: false,
cache: true,
multiple: true,
delay: 300,
onRequest: function() {
$('search2').setStyles({
'background-image':'url(indicator_blue_small.gif)',
'background-position':'350px 7px',
'background-repeat':'no-repeat'
});
},
onComplete: function() {
$('search2').setStyle('background','');
}
});
});
我们选择使用 JSON 版本的 AutoCompleter(我们也可以使用“Local”和“Request”)。 Harald 为 AutoCompleter 提供了如此多的选项,我无法在这里一一列举。我们选择展示最突出的。
我们已经创建了两个 AutoCompleter.Request.JSON 实例——一个只允许一个值,一个允许多个术语查找。为了添加一些样式并向用户传达 AutoCompleter 正在寻找类似的术语,我们根据请求添加背景图像,然后在请求完成后将其隐藏。
PHP
//settings, vars
$min = 3;
$max = 50;
$choices = 10;
$search = (string) stripslashes(strip_tags($_POST['search']));
$result = array();
//quick validation
if(strlen($search) >= $min && strlen($search) >= $max)
{
//connect to the database
$link = mysql_connect('host','username','password') or die('cannot connect');
mysql_select_db('dbname',$link) or die('cannot select db');
//query the db to find matches
$qresult = mysql_query("SELECT DISTINCT term FROM search_terms WHERE term LIKE '%".mysql_escape_string($search)."%' LIMIT $choices",$link);
//create a result array based on db results
while($row = mysql_fetch_assoc($qresult)) { $result[] = $row['term']; }
//sleep(4); // delay if you want
//push the JSON out
header('Content-type: application/json');
echo json_encode($result);
}
经过一些基本验证后,我们连接到数据库,搜索类似的术语,并返回一个 JSON 编码的字符串供 AutoCompleter 使用。
就这么简单!使用一些 PHP、CSS 和 MooTools JavaScript,您的搜索框可以从无聊和基本变得有趣和有用!
