Richie

Sometimes at night when I look up at the stars, and see the whole sky just laid out there, don't you think I ain't remembering it all. I still got dreams like anybody else, and ever so often, I am thinking about how things might of been. And then, all of a sudden, I'm forty, fifty, sixty years old, you know?

script - cancel javascript event in IE7 & FF

    The following code works correctly in IE7, FF2.0, Opera9.21, and Safari3.01, it fires the server event only when the user confirm to delete in the browser.
    the server control:
    <asp:LinkButton ID="cmdDelete" runat="server" OnClick="cmdDelete_Click"
        Text
="Delete" CssClass="linkbutton" OnClientClick="javascript:deleteConfirm(event);" />
    the javascript function:
function deleteConfirm(e)
{
    
if(!confirm("Are you sure to delete the selected items?")){
        
if(window.event && window.event.returnValue){ //for IE
            window.event.cancelBubble
=true;
            window.event.returnValue
=false
        }
        
if(e && e.preventDefault){ //for FF
            e.preventDefault();
            e.stopPropagation();
        }
    }
}  
    no test performed in IE6.

    There's another way to achieve this goal, see the following code(As Hallvord pointed out in the comments, the following code is ugly, nonstandard, and has compatibility problems. But I got this code by Google, and the original author means a way that no necessary to provider any event arguments for the function deleteConfirm(). I just found difficult to approach this and the advice for you is: do not use it in your application!):
function deleteConfirm()
{
    
if(!confirm("Are you sure to delete the selected items?")){
        
var e=getEvent();
         
if(window.event){
            e.returnValue
=false;
            e.cancelBubble
=true;
          }
else if(e.preventDefault){
            e.preventDefault();
            e.stopPropagation();
         } 
     }

function getEvent(){
     
if(window.event)    {return window.event;}
     func
=getEvent.caller;            
     
while(func!=null){    
         
var arg0=func.arguments[0];
         
if(arg0){
             
if((arg0.constructor==Event || arg0.constructor ==MouseEvent)
                 
|| (typeof(arg0)=="object" && arg0.preventDefault && arg0.stopPropagation)){    
                 
return arg0;
             }
         }
         func
=func.caller;
     }
     
return null;
    The server control is like below, this time, no event argument specified in the javascript function call in OnClientClick event.
<asp:LinkButton ID="cmdDelete" runat="server" OnClick="cmdDelete_Click"
        Text
="Delete" CssClass="linkbutton" OnClientClick="javascript:deleteConfirm();" />
    It works well in IE7, FF2.0, Opera9.21 (not include Safari3.01).

posted on 2007-06-10 18:25  riccc  阅读(1931)  评论(3编辑  收藏  举报

导航