javascript - 搜索表单重复提交时添加和删除owl carousal items
问题描述
每当通过按 Enter 提交搜索表单时,我都会使用 AJAX 调用来获取我的轮播项目。当按下 Enter 时,我想删除以前的项目并将新项目添加到轮播中。
它一直运行良好,除非反复按下 Enter,它不会删除旧项目,只是继续添加新项目。
删除项目
function removeResult() {
var i = 0;
$("#result_section").slideUp(750, function () {
$('.result_item').each(function(){
$(".prof-carousel").trigger('remove.owl.carousel', [i++])
.trigger('refresh.owl.carousel');
});
});
}
添加项目
$("#index_search_btn").click(function (e) {
e.preventDefault();
removeResult();
var formData = new FormData();
formData.append('type', search_type);
formData.append('q', search_q);
$.ajax({
type: "POST",
contentType: false,
processData: false,
url: "/search",
data: formData,
success: function (response) {
$("#result_section").slideDown(750, function () {
$.each(response, function (index, prof) {
var item = '';
item += '<div class="item carousel_ostad_item result_item">'+ 'whatever...'+'</div>';
$('.my-carousel').owlCarousel().trigger('add.owl.carousel',[jQuery(item)]).trigger('refresh.owl.carousel');
});
});
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status + " " + thrownError);
}
});
});
解决方案
我确实想出了一个简单的解决方案。我在按下时禁用了搜索按钮(因此无法重复提交表单)并在成功的 Ajax 回调中添加轮播项目后再次启用它。
$("#index_search_btn").click(function (e) {
e.preventDefault();
///// disable search button /////
$("#index_search_btn").attr("disabled", true);
removeResult();
var formData = new FormData();
formData.append('type', search_type);
formData.append('q', search_q);
$.ajax({
type: "POST",
contentType: false,
processData: false,
url: "/search",
data: formData,
success: function (response) {
$("#result_section").slideDown(750, function () {
$.each(response, function (index, prof) {
var item = '';
item += '<div class="item carousel_ostad_item result_item">'+ 'whatever...'+'</div>';
$('.my-carousel').owlCarousel().trigger('add.owl.carousel',[jQuery(item)]).trigger('refresh.owl.carousel');
///// enable search button /////
$("#index_search_btn").removeAttr("disabled");
});
});
}, error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status + " " + thrownError);
}
});
});
推荐阅读
- html - 如何仅使用 bootstrap 4 在桌面和移动设备上给出列间隙?
- sql - 在 SQL 中将字符串转换为日期
- javascript - 带有 javascript 片段的 VS Code Intellisense html 标签
- python - 将带参数的函数结果存储到变量中
- nearprotocol - (AssemblyScript + ReactJS)无法在网络共享测试上为帐户 test.near 签署交易
- c++ - 如何通过 C++ 为 v lang 创建库
- java - 验证重复项 - 在序列化类 Java 中比较 .bin 文件中的对象
- flutter - flutter 2.5.1升级后运行flutter项目出错
- swiftui - Swiftui:菜单项或选择器中的多行
- unreal-engine4 - 虚幻编辑器的问题