我也遇到了这个问题。
你可以使用window.location让浏览器访问新页面,但当前页面不会被记录在浏览器历史记录中(至少在谷歌浏览器中是如此)。
因此,我赞同SMathew的观点,应该触发新事件。但由于某些安全原因,由jQuery触发的锚点点击事件不能使浏览器访问新页面。最后,我发现以下代码可行。
$("a.confirm").on('click', function(e) {
if (!$(this).data('confirmed')) {
e.preventDefault();
var a = this;
bootbox.confirm("Are you sure?", "No", "Yes", function(result) {
if(result) {
$(a).data('confirmed', 1);
if (document.createEvent) {
var evObj = document.createEvent('MouseEvents');
evObj.initEvent('click', true, true);
a.dispatchEvent(evObj);
}
else if (document.createEventObject) {
a.fireEvent('onclick');
}
}
});
}
});
我刚在Google Chrome中测试了以上代码,并从https://getsatisfaction.com/issuu/topics/opening_the_issuu_smartlook_viewer_with_my_flash_website?utm_content=topic_link&utm_medium=email&utm_source=reply_notification找到了fire event代码。
MORE
我发现这篇文章https://dev59.com/RnRA5IYBdhLWcg3w8ikl#18132076,并且可以使用jQuery.simulate来解决这个问题。我的最终代码如下:
$("[data-toggle=confirm]").on('click', function(e) {
var a = $(this);
if (!a.data('confirmed')) {
e.preventDefault();
var question = a.data('question');
if (!question) question = 'Are you sure?';
var yes = a.data('yes');
if (!yes) yes = 'Yes';
var no = a.data('no');
if (!no) no = 'No';
bootbox.confirm(question, no, yes, function(result) {
if(result) {
a.data('confirmed', 1).simulate('click');
}
});
}
});
它适用于锚点和表单按钮。
a
被渲染到页面之后还是在ready
事件内? - Brandonbootbox.confirm
替换为 JS 警告以查看是否可以到达该点。我认为在执行preventDefault()
后,return true
不会导致链接触发。 - sachleene
对象触发事件,而不需要使用window.location的hack方法? - Justin.trigger()
,但那也会再次执行你的代码。 - sachleen