所以我有一个错误,每次我尝试点击一个元素(由我使用jquery制作的自动完成功能生成)我只能在中间点击时访问它,但是,如果我使用箭头&每次都输入它。任何想法?我的代码是。也许我只是看不到它,但我看了几个小时
{literal}
$(document).ready(function() {
function autocomplete(inp) {
var currentFocus;
var arr =[];
inp.on("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.append(a);
$.ajax({
type:"POST",
url:"//",
dataType: 'json',
data: {user_id: __st.a, keyword: val},
success: function(products) {
if(products.length){
products.forEach(function (product, index) {
b = document.createElement("div");
var div_class = "bundle_autocomplete_item_"+index;
b.setAttribute("class", div_class);
b.innerHTML = '<span style="float: left; display: block; width: 20%;"><img src="' + product.image_url + '" alt="productImageSrc"></span><span class="autocomplete-title">' + product.title + '</span>';
$(b).on("click", function(e) {
closeAllLists();
window.location.href = 'https://'+Shopify.shop+'/products/'+product.handle;
});
a.appendChild(b);
});
}
}
});
});
inp.on("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) { //up
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]);
}
}
}
}
var searchForms = $('form[action="/search"]').each(function() {
$('input[name="q"]').each(function() {
$(this).attr("autocomplete" , "off");
autocomplete($(this));
});
});
$('head').append('<style> .autocomplete {position: relative;display: inline-block;border:10px solid red;} .autocomplete-items {position: absolute;border: 1px solid #d4d4d4;border-bottom: none;border-top: none;z-index: 99;top: 100%;left:0;right: 0;overflow:hidden;white-space:nowrap;} .autocomplete-items div {padding: 7px ;cursor: pointer;background-color: #fff; border-bottom: 1px solid #d4d4d4;text-overflow:ellipsis; white-space:nowrap; overflow:hidden;}} .autocomplete-items div:hover {background-color: #e9e9e9;}.autocomplete-active {background-color: DodgerBlue !important; color: #ffffff;} .autocomplete-title{font-size:13px; margin-left:3px;</style>');});
{/literal}
我出于个人原因从ajax电话中删除了网址