jquery_auto.js文件
function autocomplete(inp, arr) {
var currentFocus;
inp.addEventListener("input", function(e) {
var a, b, i, val = this.value;
closeAllLists();
if (!val) { return false;}
currentFocus = -1;
a = document.createElement("DIV");
a.setAttribute("id", this.id + "autocomplete-list");
a.setAttribute("class", "autocomplete-items");
this.parentNode.appendChild(a)
/*for each item in the array...*/
for (i = 0; i < arr.length; i++) {
if (arr[i].substr(0, val.length).toUpperCase() == val.toUpperCase()) {
b = document.createElement("DIV");
/*make the matching letters bold:*/
b.innerHTML = "<strong>" + arr[i].substr(0, val.length) + "</strong>";
b.innerHTML += arr[i].substr(val.length);
b.innerHTML += "<input type='hidden' value='" + arr[i] + "'>";
b.addEventListener("click", function(e) {
inp.value = this.getElementsByTagName("input")[0].value;
closeAllLists();
});
a.appendChild(b);
}
}
});
inp.addEventListener("keydown", function(e) {
var x = document.getElementById(this.id + "autocomplete-list");
if (x) x = x.getElementsByTagName("div");
if (e.keyCode == 40) {
currentFocus++;
addActive(x);
} else if (e.keyCode == 38) {
currentFocus--;
addActive(x);
} else if (e.keyCode == 13) {
e.preventDefault();
if (currentFocus > -1) {
if (x) x[currentFocus].click();
}
}
});
function addActive(x) {
if (!x) return false;
removeActive(x);
if (currentFocus >= x.length) currentFocus = 0;
if (currentFocus < 0) currentFocus = (x.length - 1);
x[currentFocus].classList.add("autocomplete-active");
}
function removeActive(x) {
for (var i = 0; i < x.length; i++) {
x[i].classList.remove("autocomplete-active");
}
}
function closeAllLists(elmnt) {
var x = document.getElementsByClassName("autocomplete-items");
for (var i = 0; i < x.length; i++) {
if (elmnt != x[i] && elmnt != inp) {
x[i].parentNode.removeChild(x[i]);
}
}
}
document.addEventListener("click", function (e) {
closeAllLists(e.target);
});
}
var countries = "<?php echo ?>";
autocomplete.php文件
<?php
session_start();
error_reporting(0);
include("config.php");
$sql = mysqli_query($con,"select * from city order by cname");
while($row = mysqli_fetch_array($sql))
{
$data[] = $row['cname'];
}
echo json_encode($data);
?>
index.php
<script src="inc/jquery_auto.js"></script>
<script>
autocomplete(document.getElementById("search"), countries);
</script>
<form autocomplete="off" action="/action_page.php">
<input type="text" name="search" id="search" placeholder="Search">
</form>
在此代码中,我创建了自动完成文件。如果我仅使用var countries = ["America","Australia","India","UK"]
,它就可以正常工作,并在“自动完成”框中显示所有数据。但是,当我创建一个单独的文件autocomplete.php
并希望将此文件数据显示到我的jquery_auto.js
文件中时,它将不起作用。那么,如何解决这个问题呢?请帮助我。
谢谢