Click event not working

1
<html>
<head>
    <title>Notícia</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

</head>
<body>
    <a class="noticia" data-noticia="6" href="#">Funciona</a>
    <br>
    <a class="noticia" data-noticia="5" href="#">Funciona</a>
    <br>
    <script src="https://code.jquery.com/jquery-2.1.3.js"></script><scripttype="text/javascript">
        $(window).load(function () {
            var listaNoticias = [{
                    Id: 4,
                    Titulo: 'Testando detalhes',
                    Autor: 'José Mario',
                    Data: '10/10/2010'
                }, {
                    Id: 3,
                    Titulo: 'Testes testes',
                    Autor: 'Riv Scart',
                    Data: '10/10/2010'
                }, {
                    Id: 2,
                    Titulo: 'Testando testes',
                    Autor: 'Joab Costa',
                    Data: '10/10/2010'
                }, {
                    Id: 1,
                    Titulo: 'Testando detalhes',
                    Autor: 'Thiago Silva',
                    Data: '10/10/2010'
                }];
            var itens = "";
            $.each(listaNoticias, function (i, item) {
                itens += "<a class ='noticia' data-noticia='" + item.Id + "'  href='#'>" + item.Titulo + "</a><br>";
            });
            $('body').append(itens);
        });

        $(document).ready(function(){
            $(".noticia").click(function(){
                var id = $(this).attr('data-noticia');
                localStorage.setItem('id', id);
                alert(localStorage.getItem('id'));
            });
        });
    </script>
</body>

The problem is this: the moment I add the content of the News list in html, the added items do not work in the $ ("noticia") .click event, however the 2 items that have already been inserted work data-news 5 and 6). What can it be?

    
asked by anonymous 11.03.2015 / 14:28

2 answers

4

To work you should replace the following:

$(".noticia").click(function(){

by:

$(document).on("click", ".noticia", function(){

Because your elements are not present in the DOM when the page loads, the click event has not been 'added' to them. making the suggested substitution, even if the element is not in the DOM when the click was clicked, it will be triggered.

    
11.03.2015 / 14:32
2

When you load new items dinamicamente , the correct thing would be to use the ON event of JQuery.

In your case, it would be:

$(document).ready(function(){
    $(document).on('click', '.noticia', function(e) {
        e.preventDefault; //Não executa a ação padrão
        //Continuação
    });
});
    
11.03.2015 / 14:32