【问题标题】:HTML tag <a> want to add both href and onclick workingHTML 标记 <a> 想要同时添加 href 和 onclick 工作
【发布时间】:2013-01-29 19:49:14
【问题描述】:

我想问一下HTML标签

<a href="www.mysite.com" onClick="javascript.function();">Item</a>

如何使这个 a 标签与 hrefonClick 一起使用? (最好先运行 onClick 再运行 href)

【问题讨论】:

标签: javascript html tags onclick href


【解决方案1】:

你已经有了你需要的东西,只需要稍微改变一下语法:

<a href="www.mysite.com" onclick="return theFunction();">Item</a>

<script type="text/javascript">
    function theFunction () {
        // return true or false, depending on whether you want to allow the `href` property to follow through or not
    }
</script>

&lt;a&gt; 标签的onclickhref 属性的默认行为是执行onclick,然后只要onclick 不返回false,就跟随href,取消事件(或事件未被阻止)

【讨论】:

  • 还有没有办法用 element.addEventListener 函数做到这一点?
  • 对我不起作用,直到我把 href="#" 放在那里而不是真实的 URL。
  • 我正在使用 laravel 框架,所以在我的刀片视图中我包含了这个,它不起作用,有人用 laravel 尝试过吗?
  • 如果我在 href 的 mvc 控制器中调用了任何操作方法,则此解决方案不起作用。有人可以帮忙吗?
【解决方案2】:

使用jQuery。您需要捕获click 事件,然后继续访问该网站。

$("#myHref").on('click', function() {
  alert("inside onclick");
  window.location = "http://www.google.com";
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" id="myHref">Click me</a>

【讨论】:

  • 我不会使用任何 javascript 框架。不过谢谢你的回答
  • 以上不是实际链接。它不能在新选项卡中打开,是一种非常糟糕的做法。如果可以在新选项卡中打开某些内容(具有 na url),请始终添加一个有意义的 href 属性。
【解决方案3】:

要实现这一点,请使用以下 html:

<a href="www.mysite.com" onclick="make(event)">Item</a>

<script>
    function make(e) {
        // ...  your function code
        // e.preventDefault();   // use this to NOT go to href site
    }
</script>

这里是working example

【讨论】:

  • 这在 Chrome 中适用于我,但 Safari 似乎运行该功能但没有打开 href...任何建议?
  • @Ben 我在没有 JS 的情况下对 fiddle 进行了测试 - 只有纯 html:&lt;a href="http://example.com" &gt;Item&lt;/a&gt; 在 Chrome 中我看到一些消息允许页面运行此链接(在 chrome url 栏末尾发出警报)。在控制台的 safari 中,我看到警告:[blocked] fiddle.jshell.net/_display 的页面不允许显示来自 example.com 的不安全内容 - 所以这可能是一些安全问题(仅在小提琴上?)
【解决方案4】:

使用ng-click 代替onclick。就这么简单:

<a href="www.mysite.com" ng-click="return theFunction();">Item</a>

<script type="text/javascript">
function theFunction () {
    // return true or false, depending on whether you want to allow 
    // the`href` property to follow through or not
 }
</script>

【讨论】:

  • 仅在 AngularJS 中
【解决方案5】:

不需要 jQuery。

Some people say using onclick is bad practice...

此示例使用纯浏览器 javascript。默认情况下,点击处理程序似乎会在导航之前进行评估,因此您可以取消导航并根据需要自行处理。

<a id="myButton" href="http://google.com">Click me!</a>
<script>
    window.addEventListener("load", () => {
        document.querySelector("#myButton").addEventListener("click", e => {
            alert("Clicked!");
            // Can also cancel the event and manually navigate
            // e.preventDefault();
            // window.location = e.target.href;
        });
    });
</script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-01
    • 2012-01-29
    • 2015-09-23
    • 2014-03-09
    • 2018-07-30
    • 1970-01-01
    相关资源
    最近更新 更多