【发布时间】:2015-05-18 13:59:07
【问题描述】:
我们正在尝试实现以下要求:用户点击一个链接,我们现在需要调用一个函数,然后(假设 2000 毫秒后)执行默认链接事件(可以打开下一页,一个 mailto 链接或其他)。
我们尝试了很多类似的方法:
HTML
<a class="link-elem" href="foo.html">Foo Bar</a>
事件监听器
$('.link-elem').on('click', function(event, fromFunction) {
if (fromFunction) {
// do the default event
console.log('event triggered again with fromFunction = true');
} else {
// call function
otherFunction(event, {foo: 'bar'});
// prevent default behavior
// (tried all combinations of these)
// return false;
event.preventDefault();
event.stopPropagation();
event.stopImmediatePropagation();
}
});
其他功能
var otherFunction = function(event, otherArg) {
// do function stuff
setTimeout(function() {
// trigger event again with fromFunction = true
$(event.target).trigger(event.type, true);
}, 2000);
};
这里的 JS 小提琴:https://jsfiddle.net/kwh5tay8/
结果是我们看到了 console.log 消息,但实际事件没有发生,也就是没有加载下一页。
我们无法读取 href 属性并执行window.location 之类的操作,因为我们不能将事件视为简单链接。
有没有办法解决这个问题?
【问题讨论】:
-
什么是
otherArg?你还没有定义它。 -
它是otherFunction中使用的对象,我添加它是为了澄清。
-
应该加载的下一个页面,它是通过锚标记链接的,还是您定义了另一个事件监听器来加载它?
-
我不确定我是否理解。如果您希望发生默认行为,为什么要使用 event.preventDefault() ?我摆脱了它,它起作用了
-
首先,我们需要防止默认行为(例如打开一个新页面),因为我们需要给 otherFunction() 2000ms 的时间来做某事。然后在 2000 毫秒之后,我们不再关心,需要默认事件发生。
标签: javascript jquery events javascript-events