我想问一下 HTML 标签
<a href="www.mysite.com" onClick="javascript.function();">Item</a>
如何使其成为使用href和onClick的标签?(更喜欢先onClick运行然后href)
我想问一下 HTML 标签
<a href="www.mysite.com" onClick="javascript.function();">Item</a>
如何使其成为使用href和onClick的标签?(更喜欢先onClick运行然后href)
你已经有了你需要的东西,只需稍微修改一下语法:
<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>
<a>标签onclick和href属性的默认行为是执行onclick,然后href只要onclick不返回false,就取消该事件(或该事件未被阻止)
使用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>
要实现此目的,请使用以下 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>
这是工作示例。
不需要jQuery。
此示例使用纯浏览器 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>
使用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>