Geo*_*uer 62 javascript dom event-propagation
当用户点击某个链接时,我想用确认对话框显示它们.如果他们点击"是",我想继续原始导航.一个问题:我的确认对话框是通过返回一个jQuery.Deferred对象实现的,该对象仅在用户单击Yes按钮时解析.所以基本上确认对话框是异步的.
所以基本上我想要这样的东西:
$('a.my-link').click(function(e) {
e.preventDefault(); e.stopPropogation();
MyApp.confirm("Are you sure you want to navigate away?")
.done(function() {
//continue propogation of e
})
})
Run Code Online (Sandbox Code Playgroud)
当然,我可以设置一个标志并重新触发点击,但这很麻烦.这样做的任何自然方式?
c69*_*c69 10
以下是Chrome 13中实际工作的代码中的一些内容,令我惊讶.
function handler (evt ) {
var t = evt.target;
...
setTimeout( function() {
t.dispatchEvent( evt )
}, 1000);
return false;
}
Run Code Online (Sandbox Code Playgroud)
这不是非常跨浏览器,也许将来会修复,因为它感觉像安全风险,imho.
如果您取消事件传播,我不知道会发生什么.
它可能有风险,但至少在撰写本文时似乎有效,我们正在生产中使用它。
这是 ES6 和 React,我已经测试并发现它适用于以下浏览器。一个好处是,如果有例外(在制作过程中有几个例外),它会像正常<a>
链接一样转到该链接,但它不会是 SPA,然后是 ofc。
桌面:
手机/平板电脑:
。
import 'mdn-polyfills/MouseEvent'; // for IE11
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
class ProductListLink extends Component {
constructor(props) {
super(props);
this.realClick = true;
this.onProductClick = this.onProductClick.bind(this);
}
onProductClick = (e) => {
const { target, nativeEvent } = e;
const clonedNativeEvent = new MouseEvent('click', nativeEvent);
if (!this.realClick) {
this.realClick = true;
return;
}
e.preventDefault();
e.stopPropagation();
// @todo what you want before the link is acted on here
this.realClick = false;
target.dispatchEvent(clonedNativeEvent);
};
render() {
<Link
onClick={(e => this.onProductClick(e))}
>
Lorem
</Link>
}
}
Run Code Online (Sandbox Code Playgroud)
iri*_*uzz -2
这未经测试,但可能作为您的解决方法
$('a.my-link').click(function(e) {
e.preventDefault(); e.stopPropogation();
MyApp.confirm("Are you sure you want to navigate away?")
.done(function() {
//continue propogation of e
$(this).unbind('click').click()
})
})
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
63221 次 |
最近记录: |