2012-01-09 41 views
5

我有一個鏈接:使用JQuery onclick條件停止鏈接?

鏈接

::

$('#myID').click(function(){ 
    if($("#myCheckbox").is(":checked")) { 
     alert('Yes it is...'); //continue as normal 
    } 
    else { 
     alert('Not checked'); 
     //exit do not follow the link 
    } 

... 

所以//退出不會跟隨鏈接可能嗎?

回答

7

嘗試使用event.preventDefault()

$('#myID').click(function(e) { 
    if ($("#myCheckbox").is(":checked")) { 
     alert('Yes it is...'); 
    } 
    else { 
     alert('Not checked'); 
     e.preventDefault(); // this prevents the standard link behaviour 
    } 
} 
3

簡單:

$('#myID').click(function (e) { 
    ... 
} else { 
    alert('Not checked'); 
    e.preventDefault(); 
} 

您還可以使用return false,但是這也將停止click事件的傳播(這可能是不需要的)。

2

返回您else條件虛假。當你想在一個特定的點

3

只使用return false;。然後當你不想跟隨鏈接時,你可以做event.preventDefault()。

$('#myID').click(function(event){ 
    if($("#myCheckbox").is(":checked")) { 
     alert('Yes it is...'); //continue as normal 
    } 
    else 
    { 
     alert('Not checked'); 
     //exit do not follow the link 
     event.preventDefault(); 
    } 
}); 
2

停止操作,您可以使用event.preventDefault()

讓你的點擊功能接收該事件作爲參數

$('#myID').click(function(){ 
if($("#myCheckbox").is(":checked")) { 
    alert('Yes it is...'); //continue as normal 
} 
else { 
    alert('Not checked'); 
    return false; 
} 
1

您可以通過在活動,並與下面覆蓋默認行爲:

$('#myID').click(function(e) { 
    e.preventDefault(); 
    //exit do not follow the link 
});