禁用jQuery函数

时间:2012-02-24 03:33:52

标签: javascript jquery html

我有一个jQuery函数来监视'beforeunload'状态。 因此,每次刷新时都会执行此方法。

The function is as follows:


 <script type="text/javascript"> 

var bIsSafeRedirect = false; 

$('#reload').click(function() 
{ 
bIsSafeRedirect = true; 
location.reload(); 

}); 

$(window).bind('beforeunload', function() 
{ 
if (!bIsSafeRedirect ) 
{ 
return '>>>>>Before You Go<<<<<<<< \n Your custom message go here'; 
} 
}); 



</script>

现在我有其他组件,例如

<td onClick="window.location.replace('try.html')" id="reload" target="Content">

onclick重新加载同一页面。 我在这个场景中点击表数据我不希望调用jQuery函数。我希望它作为特殊情况被跳过。 我怎样才能实现它。

整个代码如下所示

<html> 
<head> 
<title>Refresh a page in jQuery</title> 
<script type="text/javascript" src="jquery-1.4.2.min.js"></script> 
<script type="text/javascript"> 
function load() 
{ 
document.getElementById("first").value="hello"; 
} 
</script> 
</head> 

<body> 

<h1>Stop a page from exit with jQuery</h1> 

<button id="reload">Refresh a Page in jQuery</button> 

 <script type="text/javascript"> 

var bIsSafeRedirect = false; 

function unload(type, url){ 
if(type === 'noReturn'){ 
$(window).unbind("beforeunload"); 
window.location.replace(url); 
} else if(!bIsSafeRedirect && type === 'return') { 
var conf = confirm('do you want to quit'); 
if(conf){ 
alert("ajax"); 
} else { 
return false; 
} 
} 
}  

$(window).bind("beforeunload", function(){ 
unload('return'); 
}); 



</script> 

<table> 
<tr>
<td onClick="window.location.replace('try.html')" id="reload" target="Content"> 
<td onClick="unload('noReturn','try.html')">
Usual Refresh 
</td>
</tr> 
</table> 
<input type="text" id="first" size="15"/> 
<input type="button" onclick="load()" value="load"/> 

</body> 
</html>

3 个答案:

答案 0 :(得分:3)

试试这个:

<td onClick="replaceContent();" id="reload" target="Content">

以下是replaceContent()功能:

function replaceContent(){
  $(window).unbind('beforeunload');
  window.location.replace('try.html');
}

答案 1 :(得分:2)

一种方法是将其添加到onClick

$(window).unbind('beforenload');

另一种方式是使用全局标记,与您当前使用的bIsSafeRedirect完全相同。像这样更改beforeunload处理程序主体:

if (shouldRefresh && !bIsSafeRedirect) 
{ 
    return '>>>>>Before You Go<<<<<<<< \n Your custom message go here'; 
}

并在shouldRefresh中将false值设置为onClick

答案 2 :(得分:1)

创建一个处理这两者的函数:

function unload(type, url){
    if(type === 'noReturn'){
        $(window).unbind("beforeunload");
        window.location.replace(url);
    } else if(!bIsSafeRedirect && type === 'return') {
        var conf = confirm('Confirmation message');
        if(conf){
            // fire ajax call here
        } else {
            return false;
        }
    }
}

然后在bind()电话中点击此功能:

$(window).bind("beforeunload", function(){
    unload('return');
});

由于我们将return字符串提供给type参数,因此它会触发if语句的else if部分,该部分不解除beforeunload事件的绑定,因此返回该字符串。

对于您的其他组件:

<td onClick="unload('noReturn','try.html')"></td>

现在,由于我们已将noReturn字符串提供给type参数,因此if语句的第一部分将执行并加载页面而不受beforeunload处理程序的干扰通过解除绑定。

使用此方法,您可以对多个元素的内联unload处理程序使用onclick函数,并使其成为更全局可用的脚本。