javascript prevent the default event

Copyright: the voice of experience, I do not know whether the change package spicy bar, and the other, please indicate the source. https://blog.csdn.net/zhezhebie/article/details/90753673

Let's take a closer look at the working mechanism of the event handler. After adding an element to the event handler, once an event occurs, the appropriate javascript code returns a Boolean value of true or false. As a result, when the link is clicked, the JavaScript code is returned if this value is true, onclick event handler felt that "this link is clicked"; on the contrary, if the return value is false, onclick event handler is considered " this link is not clicked. "
By following this simple test to verify this conclusion:

Test code:

<a href="http://www.baidu.com" onclick="return false;">Click me</a>

When you click on this link, because the onclick returns false, so the default behavior of the link has not been triggered.
By the same token, when we call a js method of self-defined, you can add a ** return false after calling the method onclick inside; ** statement, it appears the default behavior can be prevented.

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>SHow Pictures</title>
</head>
<body>
	<a href="http://www.baidu.com" onclick="return false;">Click me</a>
	<h3>Click Th link,show the picture.</h3>
	<div>
		<ul>
			<li>
				<a href="imgs/carrots-on-earth.jpg" onclick="showPic(this); return false;">Earth</a>
			</li>
			<li>
				<a href="imgs/flying-poodle-ears.jpg" onclick="showPic(this); return false;">Ears</a>
			</li>
			<li>
				<a href="imgs/playful-patterned-sphere-hot-air-balloon-floats-in-blue-sky.jpg" onclick="showPic(this); return false;">Sky</a>
			</li>
		</ul>
	</div>
	<img id="placeholder" src="imgs/null.jpg" width="400px" alt="">
	<script src="pic.js"></script>
</body>
</html>

pic.js Code:

function showPic(whichPic) {
    var placholder = document.getElementById("placeholder");
    var source = whichPic.getAttribute("href");
    placeholder.setAttribute('src', source);
}

The role of this code is to click on a tab in this window shows the corresponding picture.

Guess you like

Origin blog.csdn.net/zhezhebie/article/details/90753673