单击复选框并仅显示该类别的“新闻”

时间:2015-03-23 14:47:11

标签: javascript select checkbox show

所以我制作了从网站上读取新闻的代码,然后它出现在我的网站上。这是发生的事情:

我读取类别并将它们放在一个数组上,我检查它是否已经存在于数组中,如果没有,那么我在数组中添加带有.push的类别。

我需要的是单击复选框(可以单击/选中多个复选框),刷新页面并显示仅选择类别的新闻。

示例:

1
Category: A
Text

2
Category: B
Text

3
Category: B
Text

4
Category: C
Text

如果我点击“B”复选框,则只会出现#2 #3 。如果我同时点击“B”“C”复选框,#2 #3 应该出现#4

(正如您可能已经注意到的那样,我已经尝试过getElementById并重新制作,但不起作用,所以我删除了showNews函数)

知道该怎么办?我的实际代码:

var noticiasTodas;
var pagActual = 0;
var numNoticiaPag = 5;
var noticiasActuais;
var categorias;
var arrayC = [];
var count = 0;
$(document).ready(function(){
    $.getJSON("http://193.137.65.112/tpsi/noticias.php", function(dados){
        
        noticiasTodas = dados.noticias;
        categorias = [];
        setCategoria();
        escreveNoticias();
    });
});

// ------- works
function setCategoria() {
    noticiasActuais = noticiasTodas;
}

function showNews(){
    var p_body = $("#noticiasDiv");
p_body.empty();

    for(var i = 0; i < arrayC.length; i++) {
        $.each(noticiasActuais, function(index, noticiasActuais){
            
            if(noticiasActuais.categoria == arrayC[i]) {
                var linha = "<h2>"+noticiasActuais.titulo+" <span class='category'>"+noticiasActuais.categoria+"</span></h2><h4>"+noticiasActuais.subtitulo+"</h4><p class=\"paragraph\">"+noticiasActuais.artigo+"</p><p class=\"date\">"+noticiasActuais.data+"</p><hr>";
                p_body.append(linha);
            }
            
        });
    }
}

// ------- works
function escreveNoticias() {
    var p_body = $("#noticiasDiv");
    p_body.empty();
    var c_body = $("#checkboxDiv");
    c_body.empty();
    
    $.each(noticiasActuais, function(index, noticiasActuais){
        var linha = "<h2>"+noticiasActuais.titulo+" <span class='category'>"+noticiasActuais.categoria+"</span></h2><h4>"+noticiasActuais.subtitulo+"</h4><p class=\"paragraph\">"+noticiasActuais.artigo+"</p><p class=\"date\">"+noticiasActuais.data+"</p><hr>";
        p_body.append(linha);
        
        var test = arrayC.indexOf(noticiasActuais.categoria);
        if(test == -1) {
            arrayC.push(noticiasActuais.categoria);
            var check = "<input type=\"checkbox\" class=\"check\"><label class=\"checkName\">"+noticiasActuais.categoria+"</label>";
            c_body.append(check);
        }
    });
    
    var elemento = document.getElementById("checkboxDiv");
    elemento.addEventListener("click", showNews);
}
h2 {
    font-size: 15px;
    color: orangered;
    font-weight: bold;
}

.category {
    font-size: 12px;
    color: coral;
}

h4 {
    font-size: 13px;
    color: dimgray;
    font-weight: bold;
    font-style: italic;
    padding: 8px;
}

.paragraph {
    font-size: 12.5px;
    color: dimgray;
    text-align: justify;
    text-justify: inter-word;
    background-color: gainsboro;
    padding: 12px;
    border: 1px;
    border-radius: 3px;
}

.paragraph:hover {
    background-color: whitesmoke;
}

.date {
    font-size: 12px;
    color: darkslategrey;
    font-style: italic;
}

.check {
    
}

.checkName {
    margin-right: 20px;
    margin-left: 5px;
    color: coral;
    font-weight: normal;
}

.checkCont {
    display: block;
    text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Bootstrap 3, from LayoutIt!</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta name="description" content="">
  <meta name="author" content="">

	<!--link rel="stylesheet/less" href="less/bootstrap.less" type="text/css" /-->
	<!--link rel="stylesheet/less" href="less/responsive.less" type="text/css" /-->
	<!--script src="js/less-1.3.3.min.js"></script-->
	<!--append ‘#!watch’ to the browser URL, then refresh the page. -->
	
	<link href="css/bootstrap.min.css" rel="stylesheet">
	<link href="css/style.css" rel="stylesheet">

  <!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
  <!--[if lt IE 9]>
    <script src="js/html5shiv.js"></script>
  <![endif]-->

  <!-- Fav and touch icons -->
  <link rel="apple-touch-icon-precomposed" sizes="144x144" href="img/apple-touch-icon-144-precomposed.png">
  <link rel="apple-touch-icon-precomposed" sizes="114x114" href="img/apple-touch-icon-114-precomposed.png">
  <link rel="apple-touch-icon-precomposed" sizes="72x72" href="img/apple-touch-icon-72-precomposed.png">
  <link rel="apple-touch-icon-precomposed" href="img/apple-touch-icon-57-precomposed.png">
  <link rel="shortcut icon" href="img/favicon.png">
  
	<script type="text/javascript" src="js/jquery.min.js"></script>
	<script type="text/javascript" src="js/bootstrap.min.js"></script>
	<script type="text/javascript" src="js/scripts.js"></script>
</head>

<body>
<div class="container">
	<div class="row clearfix">
		<div class="col-md-12 column">
			<div class="page-header">
				<h1>
					Notícias <small>20-03-2015</small>
				</h1>
			</div>
		</div>
	</div>
        
        <!-- Checkbox -->
        <div class="checkCont">
        <div class="row clearfix">
		<div class="col-md-12 column">
                    <div id="checkboxDiv">
			
                    </div>
                    <hr>
		</div>
	</div>
        </div>
    
        <!-- Notícias -->
	<div class="row clearfix">
		<div class="col-md-12 column">
                    <div id="noticiasDiv">
			
                    </div>
		</div>
	</div>
	<div class="row clearfix">
		<div class="col-md-12 column">
			<ul class="pagination">
			</ul>
		</div>
	</div>
</div>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

你需要改变一下你的逻辑

1)每个新闻包装在容器中,类等于新闻类别

2)在复选框上更改简单切换可见所需类别

尝试查看代码段

var noticiasTodas;
var pagActual = 0;
var numNoticiaPag = 5;
var noticiasActuais;
var categorias;
var arrayC = [];
var count = 0;
$(document).ready(function(){
    $.getJSON("http://193.137.65.112/tpsi/noticias.php", function(dados){
        
        noticiasTodas = dados.noticias;
        categorias = [];
        setCategoria();
        escreveNoticias();
    });
});

// ------- works
function setCategoria() {
    noticiasActuais = noticiasTodas;
}

function showNews(){
  $('.'+this.value).toggle(this.checked); //toggle needed category
}

// ------- works
function escreveNoticias() {
   
    //generate checkboxes
    var categories = noticiasActuais.reduce(function(acc, el){
      if(!acc.map[el.categoria]){
        acc.map[el.categoria] = true;
        acc.result.push($('<input>').attr({type:"checkbox", class:"check", id:"cb"+el.categoria, value:el.categoria, checked:"checked"}));
        acc.result.push($('<label>').attr({type:"checkbox", class:"checkName", for:"cb"+el.categoria}).html(el.categoria));
      }
      return acc;
    }, {map:{}, result:[]}).result;
  
    //generate news
    var news = noticiasActuais.map(function(el){
      return $('<div>').addClass(el.categoria)
                       .append($('<h2>').html(el.titulo)
                                        .append($('<span>').addClass('category')
                                                           .html(el.categoria)))
                       .append($('<h4>').html(el.subtitulo))
                       .append($('<p>').addClass('paragraph')
                                       .html(el.artigo))
                       .append($('<p>').addClass('date')
                                       .html(el.data));
    });
    // add news to main container
    $("#noticiasDiv").empty().append(news);
    //add checkboxes to container
    $("#checkboxDiv").empty().append(categories)
    //add event handler for checkbox change
    $(':checkbox').change(showNews);
}
h2 {
    font-size: 15px;
    color: orangered;
    font-weight: bold;
}

.category {
    font-size: 12px;
    color: coral;
}

h4 {
    font-size: 13px;
    color: dimgray;
    font-weight: bold;
    font-style: italic;
    padding: 8px;
}

.paragraph {
    font-size: 12.5px;
    color: dimgray;
    text-align: justify;
    text-justify: inter-word;
    background-color: gainsboro;
    padding: 12px;
    border: 1px;
    border-radius: 3px;
}

.paragraph:hover {
    background-color: whitesmoke;
}

.date {
    font-size: 12px;
    color: darkslategrey;
    font-style: italic;
}

.check {
    
}

.checkName {
    margin-right: 20px;
    margin-left: 5px;
    color: coral;
    font-weight: normal;
}

.checkCont {
    display: block;
    text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
	<div class="row clearfix">
		<div class="col-md-12 column">
			<div class="page-header">
				<h1>
					Notícias <small>20-03-2015</small>
				</h1>
			</div>
		</div>
	</div>
        
        <!-- Checkbox -->
        <div class="checkCont">
        <div class="row clearfix">
		<div class="col-md-12 column">
                    <div id="checkboxDiv">
			
                    </div>
                    <hr>
		</div>
	</div>
        </div>
    
        <!-- Notícias -->
	<div class="row clearfix">
		<div class="col-md-12 column">
                    <div id="noticiasDiv">
			
                    </div>
		</div>
	</div>
	<div class="row clearfix">
		<div class="col-md-12 column">
			<ul class="pagination">
			</ul>
		</div>
	</div>
</div>