gpt4 book ai didi

jQuery获取li元素Ajax平滑更新

转载 作者:太空宇宙 更新时间:2023-11-04 08:28:20 24 4
gpt4 key购买 nike

我想知道如何实现平滑的自动完成 ul,问题是每当它更新时它都会闪烁,平滑我的意思是它不会闪烁,更准确地说就像谷歌一样,每次你输入something,结果列表不眨眼地更新。

我的代码:

    $("#uname").on("input", function () {
let data = {"name": $("#uname").val()};
$(".suggested-names ul li").remove(); //remove previous results
$.ajax({
url: "searchInDB.php",
method: "POST",
data: data,
dataType: "json",
success: function (response) {
for(var key in response){
$(".suggested-names ul").append("<li>" + response[key] +"</li>"); //update results
}
}
});
});

CSS:

    .suggested-names{
min-width: 100%;
background: #fff;
position: absolute;
z-index: 2;
}
.suggested-names ul{
min-width: 100%;
max-width: 100%;
margin: 0;
padding:0px;
box-shadow: #8c8c8c 0 4px 3px 0;
}
.suggested-names li{
text-decoration: none;
list-style: none;
padding:5px;
font-size: 16px;
color: #0f0f0f;
}
.suggested-names li:hover{
background: #eeeeee;
cursor: pointer;
}
.suggested-names li:last-of-type{
border: none;
}

我的代码向一个返回字符串数组的 PHP 脚本发出请求,每次用户写入或删除它更新的东西时它看起来不太好,它闪烁,我不知道如何修复它,如果你能帮助我,那就太棒了。

而且,如果有更好的方法来完成我想做的事情,我愿意倾听您的想法。谢谢

最佳答案

我建议从 ul 中删除元素仅在 success功能,因为 AJAX 是异步的,并且元素的移除和插入之间存在延迟。

$("#uname").on("input", function () {
let data = {"name": $("#uname").val()};
$.ajax({
url: "searchInDB.php",
method: "POST",
data: data,
dataType: "json",
success: function (response) {
$(".suggested-names ul li").remove(); //remove previous results
for(var key in response){
$(".suggested-names ul").append("<li>" + response[key] +"</li>"); //update results
}
}
});
});

这是一个 Fiddle论证原理。

注意:jQuery 弃用了 success功能,所以将来考虑使用 .done()相反。

来自documentation :

Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are removed as of jQuery 3.0. You can use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

另请注意,如果 response是一个数组而不是你不应该使用的对象 for(var ... in ...) for 循环,考虑使用常规 for 循环遍历它是更好的做法。
如果它是一个对象,你应该测试 response.hasOwnProperty(key) , 否则它将匹配任何扩展 Object.prototype 的用户定义属性.

关于jQuery获取li元素Ajax平滑更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44982670/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com