SoFunction
Updated on 2025-03-09

Various solutions to trigger the onclick event without jumping

When developing web pages, we often encounter the following situations:

1. A tag is just to trigger the onclick behavior;
2. The mouse pointer display should be displayed, or other visual effects similar to A-label.
For example, when performing a deletion operation, in order to avoid misoperation, we need to pop up a dialog box to let the user determine whether to delete it. Therefore, we often use the link <a></a> form to replace <button> to trigger the onclick event.
The code is as follows:
Copy the codeThe code is as follows:

<script type="text/javascript">
function del(){
if(confirm("Confirm to delete the record?") {
="Execute delete.jsp";
return true;
}
return false;
}
</script>
<a href="" target="mainFrame" class="STYLE4" onclick="del()" >Delete</a>

The consequence of this is that the js code will jump to the "Execute Delete.jsp" page, and the <a> tag will jump to open an empty page. Because the html itself processes the href attribute of the <a> tag, we will first execute the method we define, and then run its own method (jump method).

There are four main solutions, as follows:
1. Don’t use the A tag, set css or use js to express it (a bit complicated);
2. Return false in the a tag, onclick attribute or onclick event; (personal preference)
For example: <a href="" target="mainFrame" class="STYLE4" onclick="del();return false" >Delete</a>
This is a question of execution order. The execution order of this tag should be to execute the onclick script first, and then the page specified by the href parameter is finally redirected. Returning false in onclick can abort the workflow of the <a> tag, that is, prevent the page from jumping to the page specified by the href parameter.
3. Use href="javascript:void(0)" as a pseudo-protocol; (this pseudo-protocol is better to write less)
That is: <a href="javascript:void(0)" target="mainFrame" class="STYLE4" onclick="del()" >Delete</a>
4. <a href="#" class="STYLE4" onclick="del()" >Delete</a>. (Always jump to the top of the current page. When there is a lot of content on the page, you will still feel like you are jumping)