Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
296 views
in Technique[技术] by (71.8m points)

html - Simple JavaScript problem: onClick confirm not preventing default action

I'm making a simple remove link with an onClick event that brings up a confirm dialog. I want to confirm that the user wants to delete an entry. However, it seems that when Cancel is clicked in the dialog, the default action (i.e. the href link) is still taking place, so the entry still gets deleted. Not sure what I'm doing wrong here... Any input would be much appreciated.

EDIT: Actually, the way the code is now, the page doesn't even make the function call... so, no dialog comes up at all. I did have the onClick code as:

onClick="confirm('Delete entry?')"

which did bring up a dialog, but was still going to the link on Cancel.

<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jstl/fmt_rt"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>

<script type="text/javascript">

function delete() {
    return confirm('Delete entry?')
}

</script>


...

<tr>
 <c:if test="${userIDRO}">
    <td>
        <a href="showSkill.htm?row=<c:out value="${skill.employeeSkillId}"/>" />
        <img src="images/edit.GIF" ALT="Edit this skill." border="1"/></a>
    </td>
    <td>
        <a href="showSkill.htm?row=<c:out value="${skill.employeeSkillId}&remove=1"/>" onClick="return delete()"/>
        <img src="images/remove.GIF" ALT="Remove this skill." border="1"/></a>
    </td>
 </c:if>
</tr>

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There's a typo in your code (the tag a is closed too early). You can either use:

<a href="whatever" onclick="return confirm('are you sure?')"><img ...></a>

note the return (confirm): the value returned by scripts in intrinsic evens decides whether the default browser action is run or not; in case you need to run a big piece of code you can of course call another function:

<script type="text/javascript">
function confirm_delete() {
  return confirm('are you sure?');
}
</script>
...
<a href="whatever" onclick="return confirm_delete()"><img ...></a>

(note that delete is a keyword)

For completeness: modern browsers also support DOM events, allowing you to register more than one handler for the same event on each object, access the details of the event, stop the propagation and much more; see DOM Events.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...