href=“javascript:Function() 它是如何工作的

href="javascript:Function() how does it work

本文关键字:何工作 工作 javascript Function href      更新时间:2023-09-26
<a href="javascript:Function()"> Content</a>

像这样,函数如何工作?我可以拦截它,如果我不使用鼠标如何触发它?

当链接被"触发"时,即单击或按 Tab 键并按 Enter 时,它将被触发。您可以通过将Function替换为自定义函数来"拦截"它:

var oldFunc = window.YourFunction;
window.YourFunction = function() {
    // do something
    oldFunc(); // call the old function if necessary
    // do more if necessary
}

顺便说一句:你根本不应该这样做。使用onclick="..."甚至更好的方法是,通过JavaScript注册事件。当链接实际上不是鼠标单击而是通过按 Enter 触发时,这两种情况也会触发。

要使用 onclick,链接应如下所示:

<a href="#" onclick="YourFunction(); return false;">...</a>

要在现代浏览器中注册事件(v9 之前的 IE 不是现代浏览器,以防对您很重要(:

<a href="#" id="whatever">...</a>
<script>
document.getElementById('whatever').addEventListener('click', YourFunction, false);
</script>

为了保持简短和跨浏览器兼容,我强烈建议您使用jQuery:

<a href="#" id="whatever">...</a>
<script>
$('#whatever').on('click', YourFunction);
</script>

如果你想使用 href,你可以使用它

<a href="javascript:void(0);" onclick="smfunction()">Content</a>​
<script lang="javascript" type="text/javascript">
   function  smfunction(){
        alert("Running");
    }
</script>