Javascript: Onclick And Return False
Solution 1:
function preload () {
// some codereturnfalse;
}
<a href="#" onclick="return preload('12345');">Click</a>
or use addEventListener
For example:
<ahref="#"class="link">Click</a><scripttype="text/javascript">document.querySelector('.link').addEventListener('click', function (e) {
// some code;
e.preventDefault();
}, false);
</script>
Solution 2:
Putting return false;
in the inline onclick
attribute prevents the default behavior (navigation) from occurring. You can also achieve this by clobbering the onclick
attribute in JavaScript (i.e. assigning the .onclick
property to be a function that returns false), but that's frowned upon as old-fashioned and potentially harmful (it would overwrite any additional event listeners attached to that event, for example).
The modern way to prevent the <a>
element's default click behavior from occurring is simply to call the .preventDefault()
method of the triggering event from within the attached event listener. You can attach the listener the standard way, using .addEventListener()
Some examples:
// this works but is not recommended:document.querySelector(".clobbered").onclick = function() {
returnfalse;
};
// this doesn't work:document.querySelector(".attached").addEventListener("click", function() {
returnfalse;
});
// this is the preferred approach:document.querySelector(".attachedPreventDefault").addEventListener("click", function(e) {
e.preventDefault();
});
<ahref="/fake"onclick="return false;">If you click me, I don't navigate</a><br/><aclass="clobbered"href="/fake">If you click me, I don't navigate</a><br/><aclass="attached"href="/fake">If you click me, I navigate</a><br/><aclass="attachedPreventDefault"href="/fake">If you click me, I don't navigate</a>
Solution 3:
I think if you put it into the preload
function and in the onclick
event just put return false
will work. Maybe you've tried this code?
<ahref="#"onclick="return preload('12345');">Click</a>
Solution 4:
try to put the return false clause into inline function
<input onclick="yourFunction();return false;">
Solution 5:
I would maybe suggest not using onClick() and instead using similar jQuery.
Post a Comment for "Javascript: Onclick And Return False"