我已经知道如何从数据库/ sql的角度设计建议,但是我不知道如何进行基本设计,即实际使文本字段显示带有建议的下拉列表。我认为最好的例子是以下链接:http://forums.zybez.net/runescape-2007-prices

其中有一个字段显示:“查找价格”。如果您开始输入,它将轮询数据库(我假设),并为您提供一个下拉列表。我试图弄清楚该怎么做。

为简单起见,我对使用数组的示例感到非常满意,一旦开始键入,该数组总是会弹出相同的内容。

我已经看过了,也许我只是看错了,但我完全不知所措,因为没有HTML元素(我可以找到)允许您在文本字段中输入内容下拉框。

最佳答案

将事件侦听器添加到输入字段:

input.addeventlistener('change', function () {
    var response = callServer(),
        arr = JSON.parse(response),
        parentDiv = document.getElementById('list');

    //fill the options in the document
    for(var x = 0; x < arr.length; x++) {
        var span = document.createElement('span');
        span.innerHTML = response[x].someOption;

        //add each autocomplete option to the 'list'
        parentDiv.appendChild(span);
    };

    //show the list with all the spans within it
    parentDiv.style.display = 'block';
});


然后,当输入更改时,调用callServer函数,该函数将ajax查询发送到url并返回JSON对象:

function callServer () {
    xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function(){
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
            //return the JSON object
            return xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET", url, true);
    xmlhttp.send();
}


只需从您的服务器返回一个JSON对象即可使用javascript进行解析。要使选项看起来像“下拉列表”,只需创建一个div元素,设置div的样式以确保它出现在该元素下方,然后使用动态创建的跨度填充div。

因此,动态创建的HTML如下所示:

<div id='list'>
    <span>Some Option 1</span>
    <span>Some Option 2</span>
    <span>Some Option 3</span>
    <span>Some Option 4</span>
</div>


其余效果(如:hover)是使用CSS完成的。您还可以在每个跨度中甚至添加一个onclick来模拟用户选择该选项。

关于javascript - HTML —输入[TEXT]下拉列表,并提供相关建议,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29998768/

10-12 07:01