Home  >  Article  >  Web Front-end  >  Add click event to a tag to block href jump page

Add click event to a tag to block href jump page

PHP中文网
PHP中文网Original
2016-08-20 08:47:541508browse

We commonly use click events in the a tag:
1. a href="javascript:js_method();"

This is a commonly used method on our platform, but this method fails when passing parameters such as this It is easy to cause problems, and when the javascript: protocol is used as the href attribute of a, it will not only cause the window.onbeforeunload event to be triggered unnecessarily, but also cause the gif animated picture to stop 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, which represents the role of top. So using this method to click on the web page returns to the top of the page.

5.a href="#" onclick="js_method();return false;"

This method returns false after clicking to execute the js function. The page will not jump. After execution, it will still be in the current page of the page. Location.

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 function in a is recommended:

Personally recommend the second one:

a href="javascript:void(0);" onclick="js_method()"
a href="javascript:;" onclick="js_method()"
a href="#" onclick="js_method();return false;"

The above is the content of adding click event to block href jump page in a tag, more For related content, please pay attention to the PHP Chinese website (www.php.cn)!



Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn