简体   繁体   中英

JavaScript: onclick and return false

I'm using this in my HTML:

 <a href="#" onclick="preload('12345');return false;">Click</a>

It calls the function preload() on an external js-file and works fine so far.

But i have dozens of those links and would like to remove alle those "return false" and put only one directly inside the preload()-function in the js-file.

But it will always be ignored?! Does the "return false" really only work inside the onclick="..."?

function preload () {
    // some code
    return false;
}

<a href="#" onclick="return preload('12345');">Click</a>

or use addEventListener

For example:

<a href="#" class="link">Click</a>
<script type="text/javascript">
    document.querySelector('.link').addEventListener('click', function (e) {
        // some code;

       e.preventDefault();
    }, false);
</script>

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 (ie 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() { return false; }; // this doesn't work: document.querySelector(".attached").addEventListener("click", function() { return false; }); // this is the preferred approach: document.querySelector(".attachedPreventDefault").addEventListener("click", function(e) { e.preventDefault(); });
 <a href="/fake" onclick="return false;">If you click me, I don't navigate</a><br/> <a class="clobbered" href="/fake">If you click me, I don't navigate</a> <br/> <a class="attached" href="/fake">If you click me, I navigate</a> <br/> <a class="attachedPreventDefault" href="/fake">If you click me, I don't navigate</a>

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?

<a href="#" onclick="return preload('12345');">Click</a>

尝试将return false子句放入内联函数中:

<input onclick="yourFunction();return false;">

我可能会建议不要使用 onClick() 而是使用类似的 jQuery。

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