2012-01-09 17 views
5

Tengo un enlace:JQuery onclick condition stop link?

Enlace

usando ::

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

... 

también lo es // salida no siguen el vínculo posible?

Respuesta

7

Intente utilizar 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

simple:

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

También puede utilizar return false, pero esto también se detendrá la propagación del evento click (que podría ser no deseado).

2

Volver falsa en su condición de persona.

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

sólo tiene que utilizar return false; cuando se desea detener la acción en un punto

2

específica Puede utilizar event.preventDefault()

Deje que su función click-recibir el evento como un parámetro. Entonces puedes hacer event.preventDefault() cuando no quieras seguir el enlace.

$('#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(); 
    } 
}); 
1

Puede pasar en el evento, y anular el comportamiento por defecto con lo siguiente:

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