How to prevent a link from working on a child element? (jQuery)

0

Imagine the following code below:

<a id="link" href="/nova_pagina.php">
    <div id="abrir-nova-pagina"     >Linha_1</div>
    <div id="nao-abrir-nova-pagina" >Linha_2</div>
<a/>

I want the # link element to work when I click on the first div and open a new page and I do not want the link to work when I click on the second div.

How can I do this?

I have seen some examples with jQuery using the stopPropagation () method but it did not work.

See below:

$('a#link').on('click', function(event){
    event.stopPropagation();
});

$('#nao-abrir-nova-pagina').on('click', function(event){
    alert('Funcionou!')
});

What did I do wrong?

    
asked by anonymous 16.11.2018 / 19:07

1 answer

0

event.stopPropagation() goes to the event propagation (in the case onClick ) in other elements. In the example below if you comment on this code, and click on div#nao-abrir-nova-pagina it will display alert('funcionou') and then alert(2) .

event.preventDefault() does it will not perform the default action in this case <a href>

$('a').on('click', function(event){
    alert(2);
});

$('#nao-abrir-nova-pagina').on('click', function(event){
    event.stopPropagation(); /// não propaga o click
    event.preventDefault(); /// não executa o <a href>
    alert('Funcionou!')
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><aid="link" href="/nova_pagina.php">
    <div id="abrir-nova-pagina"     >Linha_1</div>
    <div id="nao-abrir-nova-pagina" >Linha_2</div>
<a/>
    
16.11.2018 / 19:21