如果执行锚点href链接,则禁用onClick事件 [英] Disable onClick event if anchor href link was executed

查看:122
本文介绍了如果执行锚点href链接,则禁用onClick事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张桌子。
每一行都是指向某个页面的链接(例如google.com),该页面由js onClick window.open 方法调用:

I have a table. Each row is a link to some page(for example - google.com) which called by js "onClick window.open" method:

<tr  class='tr' onClick="win=window.open('http://google.com');win.focus();" >

在上一栏中,我有 主播href 链接到其他页面(例如 - jsfiddle ):

In the last column I have an anchor href link to other page (for example - jsfiddle):

<td class='td'><a href = "http://jsfiddle.net">JSFiddle</a></td>

如果我点击锚链接它已打开,但也打开了onClick调用的第一页。

If I click on anchor link it's opened, but also opened the first page called by onClick.

我发现了一个相反的问题:

I've found a reverse issue:

如果执行onclick,如何禁用HREF?

我们可以通过向onClick事件添加return false来禁用href。

We can disable href by adding "return false" to onClick Event.

如果单击锚链接,是否可以阻止onClick执行?

Is it possible to prevent onClick executing if anchor link was clicked?

以下是我的演示: 小提琴

Here is my demo: Fiddle

推荐答案

我建议你稍微改变方法。内联事件处理程序永远不是一个好主意。请考虑此代码。

I would recommend you to change approach a little. Inline event handlers are never good idea. Consider this code.

HTML:

<table id="table">
    <tr data-url="http://google.com">
        <td>Content</td>
        <td>Content</td>
        <td><a href="http://jsfiddle.net">JSFiddle</a></td>
    </tr>
    ...
</table>

JS:

var table = document.getElementById('table');

table.addEventListener('click', function(e) {

    var target = e.target;
    if (target.tagName == 'A') {
        return false;
    }

    if (target.tagName == 'TD') {
        var win = window.open(target.parentNode.getAttribute('data-url'));
        win.focus();
    }
}, false);

这篇关于如果执行锚点href链接,则禁用onClick事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆