简体   繁体   中英

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

<a href="javascript:Function()"> Content</a>

这样,功能如何工作?我可以拦截它吗?如果不使用鼠标,如何触发它?

It will be triggered when ever the link is "triggered", ie on click or when tabbing to it and pressing ENTER . You can "intercept" it by replacing Function with a custom function:

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

By the way: You shouldn't do this at all. Use onclick="..." or even better, register an event via JavaScript. Both cases will also trigger when the link is not actually mouse-clicked but triggered by pressing ENTER .

To use onclick, the link should look like this:

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

To register the event in a modern browser (IE before v9 is not a modern browser in case it matters to you):

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

To keep it short and cross-browser compatible I'd highly suggest you to use jQuery :

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

You can use this if you want to use href

<a href="javascript:void(0);" onclick="smfunction()">Content</a>​

<script lang="javascript" type="text/javascript">
   function  smfunction(){
        alert("Running");
    }
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM