我有另一个问题:有没有办法用javascript动态更改输入自动完成值?
示例:
<input id="myInput"
placeholder="Write something here..."
onchange="changeAutocompleteValue(event)">
<script>
function changeAutocompleteValue(event)
{
var list = ["first", "second", "third"];
event.list = list;
}
</script>
Google示例:
我能用普通的JS做到吗?任何建议都会很棒:)。
答案 0 :(得分:1)
我找到了
javascript : Auto complete javascript text field
如果使用现有的库那么
function loadXMLDoc(_target, _type,_func) {
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 ) {
if(xmlhttp.status == 200){
data = JSON.parse(xmlhttp.responseText);
_func(data);
}
else if(xmlhttp.status == 400) {
alert('There was an error 400')
}
else {
alert('something else other than 200 was returned')
}
}
}
xmlhttp.open(_type, _target, true);
xmlhttp.send();
}
function ontxtChange(){
var dcc = document.getElementById('autocc');
var dc = document.getElementById('autoc');
dcc.innerHTML = ' ';
var i = 0;
var target = "https://api.github.com/users/mralexgray/repos"
//
if(dc.value.length > 0){
loadXMLDoc(target,'GET',function(data){
data.forEach(function(x){
if(i < 10){
if(x.name.toLowerCase().indexOf(dc.value.trim()) != -1){
dcc.innerHTML += '<p class="accItem">' + x.name.toLowerCase() + '</p>';
i++;
}
}
});
});
}
}
&#13;
.accItem{
background-color:#333;
color:#fff;
width:200px;
}
#autocc{
width:200px;
}
&#13;
<body>
<input type="text" id="autoc" onkeypress="ontxtChange()" > example : "am"
<div id="autocc">
</div>
</body>
&#13;
建议 -
答案 1 :(得分:0)
这是可能的,但您需要编写更多代码。您最好的选择是使用现有的库来为您处理: