Bootstrap Carousel切换事件触发过晚,获取图片信息错误如何解决?
问题根本原因
你当前监听的是轮播控制按钮的点击事件,点击触发回调时轮播的滑动动画还未执行,active 类仍绑定在上一张幻灯片上,因此拿到的是旧图片的信息。同时你代码里的上一张按钮选择器写错了,.carousel-control-previous 并不存在,正确类名是 .carousel-control-prev,所以上一张切换的回调本来就不会触发。
解决方案
直接使用 Bootstrap Carousel 官方提供的滑动完成事件 slid.bs.carousel,该事件会在轮播滑动动画完全结束、新幻灯片已经被激活(active 类已切换到新项)之后才触发,完全符合你的需求。
修改后的JavaScript代码
@section Scripts { <script> function showPhotoDetails() { var url = $('.carousel-item.active img').attr('src'); var photopath = url.split('?'); photopath[0] = photopath[0].substring(8, photopath[0].length); $.ajax({ type: 'POST', url: "/Photos/GetValue?path=" + photopath[0], dataType: "json", async: false, success: function (data) { $("input#txtCreatedBy").val(data.createdBy); $("input#txtDateCreated").val(data.dateCreated); $("textarea#txtNotes").val(data.notes); } }); } $(document).ready(function () { showPhotoDetails(); $('.custom-file-input').on("change", function () { var fileLabel = $(this).next('.custom-file-label'); var files = $(this)[0].files; if (files.length > 1) { fileLabel.html(files.length + ' files selected.'); } else if (files.length == 1) { fileLabel.html(files[0].name); } }); // 替换原来的按钮点击监听,用滑动完成事件 $('#divCarousel').on('slid.bs.carousel', function () { showPhotoDetails(); }); }); </script> }
该事件兼容 Bootstrap 4 和 Bootstrap 5 所有版本,不管是点击控制按钮、点击指示器、还是自动轮播,只要切换完成都会触发该事件,不用单独监听多个交互入口。
内容的提问来源于stack exchange,提问作者user1633508
相关产品推荐
相关产品推荐

