Javascript 拦截Famo.us中的链接点击

Javascript 拦截Famo.us中的链接点击,javascript,events,event-handling,click,famo.us,Javascript,Events,Event Handling,Click,Famo.us,假设有一个使用Famo.us声明的曲面包含标记内容: this.mySurface = new Surface({ size : this.options.targetSize, content : '<a href="http://famo.us">This is a link</a>', }); this.mySurface=新曲面({ 大小:this.options.targetSize, 内容:“”, }); 有没有(简单的)方法来拦截点击事件

假设有一个使用Famo.us声明的曲面包含标记内容:

this.mySurface = new Surface({
    size : this.options.targetSize,
    content : '<a href="http://famo.us">This is a link</a>',
});
this.mySurface=新曲面({
大小:this.options.targetSize,
内容:“”,
});
有没有(简单的)方法来拦截点击事件


额外好处:除了拦截单击外,如何传递单击事件,以便默认处理程序也执行其任务?

您不能直接在曲面中打开新链接,但可以添加类似IFrameSurface的内容:

正如aintnorest所暗示的,您很可能希望向曲面的单击添加事件处理程序:

this.mySurface.on('click', function(e) {
    // Bonus: on click do the standard redirect on main window
    // or redirect of iFrame control
    window.location = "http://famo.us";
});
然后,您只需要文本“This is a link”(这是一个链接),而不是内容中的href,因为处理程序提供了通常预期的逻辑,但通过截取

如果出于某种原因需要将它们保留为“链接”,您可以尝试向href添加哈希,以避免通过默认行为进行实际导航

另一种选择是,因为我们使用的是javascript,所以您可以尝试以下方法:


有几种方法可以处理事件停止。我认为这是一个最适合你的解决方案。当然,以这种方式加载页面或链接有它自己的警告,我们在这里不会深入讨论

以下是完整代码:

首先,我们跟踪目标曲面内的点击,并调用函数检查它是否为链接。如果单击某个链接,我们将发出一个传递目标href的事件

this.mySurface.clickNullifier = function (e) {
    if (e.target && e.target.nodeName == 'A' && e.target.href) {
        this.mySurface.emit('href-clicked', { data: { href: e.target.href } })
        return false;
    }
}.bind(this);

this.mySurface.on('deploy', function () {
    // sets up the click function on the surface DOM object
    this._currentTarget.onclick = this.clickNullifier;
});
既然跟踪了表面点击,我们将捕获任何截获的点击并将它们加载到iFrame中,或者如果本地链接使用著名的loadURL实用程序将它们加载到iFrame中

this.mySurface.on('href-clicked', function (event) {
    console.log(event.data);
    // handle your code for the iframe
    // not always doable in the case of 'X-Frame-Options' to 'SAMEORIGIN'
    loadIframe.call(this, event.data.href);

    // or loadURL like here. Needs CORS open on the href server if cross origin
    //Utility.loadURL(event.data.href, loadLink.bind(this));
}.bind(this));

function loadIframe(content) {
    this.backSurface.setContent('<iframe src="' + content + '" frameborder="0" height="100%" width="100%"></iframe>');
};
this.mySurface.on('href-clicked',函数(事件){
console.log(事件数据);
//处理iframe的代码
//在“X-Frame-Options”到“SAMEORIGIN”的情况下并不总是可行的
loadIframe.call(这个,event.data.href);
//或者像这里这样加载URL。如果跨源,则需要在href服务器上打开CORS
//Utility.loadURL(event.data.href,loadLink.bind(this));
}.约束(这个);
函数loadIframe(内容){
this.backSurface.setContent(“”);
};

奖励:在上面的示例链接中,您将看到单击事件仍然会在曲面上触发。您可以通过查看控制台日志来查看。

您想用它做什么?你说的奖金是什么意思。如果在('click',function(){})上放置this.mySurface.on('click',function(){});它将捕获点击事件,让您对其进行操作,并且链接仍然被跟踪。关于你尝试做什么,我相信我能帮助你。表面包含带有链接的标准标记。我希望能够在页面的新表面中打开链接,而不是让浏览器通过在新窗口/选项卡中打开来处理链接。谢谢。这适用于单个链接,但如果标记内容包含多个(不同)链接,则不起作用+截取线程为1。这很好。谢谢talves!不客气:)我相信我最终会需要这个的。