如何复制类似美味的可点击标签?

时间:2011-02-05 21:25:50

标签: javascript html ajax

我有一个可能的标记词列表,我想在文本输入字段下面显示它们作为可点击的单词。点击后,这些单词将从下方消失(将接受没有此功能的答案)并重新出现在文本输入字段中。

已添加奖励包括从输入字段中删除添加的标记的功能(a la Delicious),但不如上述功能重要。

2 个答案:

答案 0 :(得分:2)

我对一个被误解的问题的回应:

所以基本上你想要一个标签输入的自动完成功能? AJAX的经典案例! :)

首先,您需要一个服务器端脚本,它将返回与用户已键入的字符匹配的所有标记。这个脚本可以例如查询所有标签的MySQL数据库。性能提示:确保tag - 字段是索引,因此MySQL可以更快地找到标记。服务器的响应可以是可能标记的JSON或XML列表。

然后,你需要一个JavaScript,在每次击键时调用这个服务器端脚本(也许你想添加一点延迟,所以服务器不会被请求推翻)。然后JavaScript将从服务器解析JSON或XML并将其打印为HTML。

我认为这里没有人会为你编写代码(至少不是免费的),但我相信你能够做到这一点,因为这是一个非常常见的任务,谷歌也一定会有所帮助。 / p>


编辑顺便问一下,你知道我的名字没人吗?我实际上写了一些示例代码来帮助您入门。

ajax.php:

// Add Databse-connection stuff right here

$q = strtolower ( $_GET['q'] );
if ( empty ( $q ) )
    die ( '' );

// Select all the tags that begin with the already-typed letters ($_GET["q"])
$query = "SELECT `tag` FROM `tags` WHERE `tag` LIKE ".mysql_real_escape_string($q)."_% LIMIT 10";
$did = mysql_query ( $query );
if ( !$did )
    die ( '' );

$tags = array ();
while ( $tag = mysql_fetch_row($result) ) {
    $tags[] = $tag[0];
}

// Yes, I actually didn't use any JSON or XML here, just a comma-seperated list
$ret = implode ( ",", $tags );

echo $ret;

autocomplete.js:

var tags_input = document.getElementById("tags");
var timeout = 500; // If the user doesn't type for this amount of miliseconds, the AJAX request gets sent. To protect the server a little bit. :)

var xhr;
var do_ajax = false; // Gets true after 500 ms of not typing

var tags = [];

tags_input.onkeyup = function (e) {
    if ( !e ) e = window.event;

    do_ajax = false;

    window.setTimeout ( function () {
        do_ajax = true;
        ajax_request();
    }, 500 );

};

function ajax_request () {
    var q = tags_input.value;
    if ( q == '' )
        return;
    xhr = new XMLHttpRequest;
    xhr.open ( 'GET', 'ajax.php?q='+q, true );
    xhr.send ( null );
    xhr.onreadystatechange = function () {
        if ( xhr.readyState == 4 ) {
            if ( xhr.responseText != '' ) {
                tags = xhr.responseText.split ( ',' );
                show_autocompletions();
            }
        }
    };
}

function show_autocompletions () {
    alert ( tags.join ( ', ' ) ); // you might want to generate some real HTML here
}

此示例的表结构:该表名为tag,它包含唯一的字段tag,这是一个唯一索引。确保tag不包含任何逗号。

答案 1 :(得分:2)

实际上,delicous中的标签不在输入字段中。它看起来就像那样。 我正在研究一个像标签领域一样美味的东西。但仍未准备好使用。 http://www.superbly.ch/?p=31

但你可以在这里找到更好的变种。 http://roberto.open-lab.com/2010/02/10/a-delicious-javascript-tagging-input-field/