HTML标记<a>想要添加href和onclick工作

116 html javascript tags onclick href

我想问一下HTML标签

<a href="www.mysite.com" onClick="javascript.function();">Item</a>
Run Code Online (Sandbox Code Playgroud)

如何使这一个标签与工作HREF的onClick?(首选onClick先运行然后再运行)

Ian*_*Ian 215

通过轻微的语法更改,您已经拥有了所需的内容:

<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>
Run Code Online (Sandbox Code Playgroud)

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

  • 对我来说不起作用,直到我把'href ="#"`放在那里而不是真正的URL. (2认同)

Sud*_*jee 10

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

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

  • 我不会使用任何JavaScript框架.但是谢谢你的回答 (11认同)
  • 以上不是实际链接.它无法在新标签中打开,是一种非常糟糕的做法.如果可以在新选项卡中打开某些内容(具有na url),请始终添加有意义的`href`属性. (6认同)

Kam*_*ski 6

要实现此目的,请使用以下 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>
Run Code Online (Sandbox Code Playgroud)

这是工作示例


Tea*_*man 6

不需要 jQuery。

有人说用onclick是不好的做法......

此示例使用纯浏览器 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>
Run Code Online (Sandbox Code Playgroud)