我正在尝试打开模式并更改 url 但仍停留在同一页面上。所以它应该只打开一个模式更改 url,然后当弹出窗口关闭时它只会删除添加的 URL。
我有一个在点击时更改 URL 的脚本,但如果我在点击时设置它,它会更改 url,但模式不会打开。所以我确定需要以某种方式检测模式是否打开/关闭来完成。
我的 jQuery 代码:
$(".modal").click(function() {
window.history.pushState("obj", "newtitle", "/newurl");
return false;
});
第二次尝试:
if ($(".feedModal").hasClass("show")) {
window.history.pushState("obj", "newtitle", "/abc");
return false;
});
我将 Bootstrap 用于模式,我看到我可以使用 bs.modal.shown
检测模式打开,但它对我不起作用。我也尝试了 shown
仍然没有帮助。
任何帮助都意义重大。谢谢!
最佳答案
您的代码建议您单击 $(".feedModal")
元素以打开或关闭模式。如果不是这种情况,那么这可以很容易地修改。不过,这会对您有所帮助。
如果使用psuedo-selector :visible
模式已经可见,请检查触发器上的点击事件。如果使用 Bootstrap Modal 的 .modal('hide')
方法隐藏它.这将隐藏它并触发我们稍后将使用的事件。如果它不可见,用 .modal('show')
显示它。
var $modal = $('.feedModal');
var $modal.on('click', function(event) {
if ($modal.is(':visible')) {
$modal.modal('hide');
} else {
$modal.modal('show');
}
});
如果使用 show.bs.modal
和 hide.bs.modal
事件处理程序打开或关闭模态,我们可以监听模态。通过在模式打开时监听,我们将历史更改为新值。通过在模式关闭时进行监听,我们将其更改回之前的状态。
var $feedModal = $('#feedModal');
// Listen for modal hide and popstate events.
function startListening() {
$feedModal.on('hide.bs.modal', onModalHide);
$(window).on('popstate', onPopState);
}
// Stop listening for modal hide and popstate events.
function stopListening() {
$feedModal.off('hide.bs.modal', onModalHide);
$(window).off('popstate', onPopState);
}
// Modal opens.
// Add event listeners and push state.
function onModalShow() {
startListening();
window.history.pushState({}, '', '/abc');
}
// Modal hides.
// Remove event listeners and go back.
function onModalHide() {
stopListening();
window.history.back();
}
// Navigation occurs.
// Remove event listeners and hide modal.
function onPopState() {
stopListening();
$feedModal.modal('hide');
}
// Listen for when the modal shows.
$feedModal.on('show.bs.modal', onModalShow);
关于javascript - 打开模态,然后在不重定向的情况下更改 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59473785/