显示元素包含单词

时间:2018-10-05 13:20:48

标签: javascript jquery

我有2篇文章。一篇文章具有类别-新闻,而另一篇文章具有类别-设计。我想显示具有类别新闻的文章,但其他文章将隐藏。怎么做?

	     <div class="article">
    <div class="title_article">
	<h2>News about you</h2>
	<div class="description">
	    <p> Lorem, ipsum dolor sit amet consectetur adipisicing elit. Ex mollitia dolores dignissimos velit voluptas.
		    Hic perspiciatis dolorum ullam delectus voluptatibus atque nobis aspernatur! Consequatur quo eos delectus! 
			Laboriosam, reprehenderit vel. </p>
	    <p class="category"> <span>category</span>: News </p>
        </div>
    </div>
   <a href="news/article.php">
   <div class="article">
       <div class="title_article">
           <h2>Design about you</h2></a>
               <div class="description">
	           <p> Lorem, ipsum dolor sit amet consectetur adipisicing elit. Ex mollitia dolores dignissimos velit voluptas.
		    Hic perspiciatis dolorum ullam delectus voluptatibus atque nobis aspernatur! Consequatur quo eos delectus! 
			Laboriosam, reprehenderit vel. </p>
		   <p class="category"> <span>category</span>: Design </p>
               </div>
           </div>
      

2 个答案:

答案 0 :(得分:1)

您可以使用CSS。

// style.css

.hide {
  display:none;
}

// index.html

<div class="hide"/>

答案 1 :(得分:1)

不远处,但是如果您正在寻找一些jQuery函数,则应该可以使用这种功能...

此外,您的HTML严重不平衡,因此我尝试对其进行修复以使其更有意义。

function showByCategoryText(catText) {
  $('.article').hide()
    .filter(function() {
      return $(this).find('p.category').html().indexOf(catText) !== -1;
    }).show();
}

function showNews() {
  showByCategoryText("News");
}

function showDesign() {
  showByCategoryText("Design");
}

showNews();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="article">


  <div class="title_article">
    <h2>News about you</h2>
  </div>
  <div class="description">
    <p> Lorem, ipsum dolor sit amet consectetur adipisicing elit. Ex mollitia dolores dignissimos velit voluptas. Hic perspiciatis dolorum ullam delectus voluptatibus atque nobis aspernatur! Consequatur quo eos delectus! Laboriosam, reprehenderit vel. </p>
    <p class="category"> <span>category</span>: News </p>
  </div>
</div>


<div class="article">


  <a href="news/article.php">
    <div class="title_article">
      <h2>Design about you</h2>
    </div>
  </a>
  <div class="description">
    <p> Lorem, ipsum dolor sit amet consectetur adipisicing elit. Ex mollitia dolores dignissimos velit voluptas. Hic perspiciatis dolorum ullam delectus voluptatibus atque nobis aspernatur! Consequatur quo eos delectus! Laboriosam, reprehenderit vel. </p>
    <p class="category"> <span>category</span>: Design </p>
  </div>
</div>

<button onclick="showNews();">showNews</button>
<button onclick="showDesign();">showDesign</button>