jquery, prevenir onclick = window.location no elemento pai
-
03-07-2019 - |
Pergunta
Eu tenho uma tabela com dados como este:
<table>
<tr onclick="window.location='download.php?id=1'">
<td>Program 1<br/>Short Description 1 (<a onclick="$.popup.show('Install Instructions', 'Instructions pulled from DB here')">Instructions</a>)</td>
<td>Added by user and date/time here<td>
<td>Filesize here<td>
<td><a href="edit.php?id=1">Edit</a> - <a href="delete.php?id=1">Delete</a><td>
</tr>
(repeat TRs for more programs pulled from DB)
</table>
O problema que estou tendo é que quando você clica no link (Instruções), deve aparecer uma janela com as instruções. Ele faz isso, mas ele também dispara o TR é onclick. Então eu recebo o popup para uma fração de segundo, em seguida, ele vai para download.php.
Existe alguma maneira eu posso impedi-lo de disparar da TR onclick? De preferência usando jQuery, mas eu não me importo de soluções javascript simples também.
Solução
Basicamente, você precisa parar propagação de eventos , usando event.cancelBubble ( para IE) ou event.stopPropagation () (para todos os outros). O href="http://www.quirksmode.org/js/events_order.html#link9" rel="nofollow noreferrer"> solução (que eu usei antes) é fazer algo como isto:
<script type="text/javascript">
var instructions = function(e) {
// Get the correct event in a cross-browser manner, then stop bubbling/propagation.
if (!e) var e = window.event;
e.cancelBubble = true;
if (e.stopPropagation) e.stopPropagation();
// Do what you want now
$.popup.show('Install Instructions', 'Instructions pulled from DB here');
}
</script>
Em seguida, o script seria chamá-lo:
<td>Program 1<br/>Short Description 1 (<a onclick="instructions(event)">Instructions</a>)</td>
(Claro, você poderia colocar tudo isso em linha, mas isso é uma confusão sangrenta.)
Você também pode encontrar esta questão iluminando .
Outras dicas
stopPropogation é o que deseja.
http://docs.jquery.com/Events/jQuery .Event # event.stopPropagation.28.29
Você pode escrever
onclick="false"
e eventos add usando nível modelo de evento 2 (attachEvent no IE ou addEventListener em outros navegadores). Você pode também você jquery bind ( 'clique') se você usar jQuery.