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>
<script type="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 listNoticias in html, the added items do not work in the $(".noticia") event. click(), however the 2 items that have already been entered work (data-news 5 and 6). What can be?
For dynamic items you need to use the ON, in your case would be
$(document).on('click', '.noticia', function(e) {e.preventDefault;//Continuação})
– Rafael Withoeft
Problem solved. Thank you!
– Leomar de Souza
Don’t forget to mark one of the answers as correct.
– Richard Dias