This article mainly introduces to you the relevant information about how the a tag calls JavaScript. The article introduces it in great detail through sample code. It has certain reference and learning value for everyone. I hope it can help everyone.
We commonly use click events in the a tag:
A relative or absolute URL to a valid document, including fragment identifiers and JavaScript snippets.
## The href="javascript:;" here, where javascript: is a pseudo-protocol, allows us to call javascript functions through a link. In this way javascript: ;When the click event of the A tag is running, if the page contains a lot of content and there is a scroll bar, the page will not jump around and the user experience will be better
1.
a href="javascript:js_method();"
This is a commonly used method on our platform, but this method is prone to problems when passing parameters such as this, and when the javascript: protocol is used as the href attribute of a, it will not only cause unnecessary Triggering the window.onbeforeunload event will stop the GIF animated image from playing in IE. W3C standards do not recommend executing javascript statements in href
2.
a href="javascript:void(0);" onclick="js_method()"
This method is the most commonly used method on many websites and is also the most common. A comprehensive method, the onclick method is responsible for executing the js function, and void is an operator. void(0) returns undefined, and the address does not jump. And this method does not directly expose the js method to the status bar of the browser like the first method.
3.
a href="javascript:;" onclick="js_method()"
This method is similar to the 2 methods, the only difference is that an empty js code is executed.
4.
a href="#" onclick="js_method()"
This method is also a very common code on the Internet. # is a method built into the tag, representing the role of top. So using this method to click on the web page returns to the top of the page. If the page has a scroll bar, click it and the page will return to the top of the page
a href="#" onclick="js_method();return false;"
I took a look at taobao’s homepage. They use the second method, while alibaba’s homepage uses the first method. The difference from ours is that the javascript methods in each href are surrounded by try and catch. . Based on the above, the most appropriate method to call js functions in a is recommended: a href="javascript:void(0);" onclick="js_method()"
a href="javascript:;" onclick="js_method()"
a href="#" onclick="js_method();return false;"
Related recommendations:
Several methods of calling js in a tagSummary of click events for calling js function in a tag## Several methods of calling javascript methods in a tags and window.open()
The above is the detailed content of How a tag calls JavaScript. For more information, please follow other related articles on the PHP Chinese website!