简体   繁体   中英

How can I sort divs / posts with multiple classes?

I want to make a tag system for my blog posts. If you click on the respective tag it should only show posts that contain this tag and hide the rest. So I tried to write an onClick-function but it failed. Why?

That's the HTML for the posts:

<div class="post lorem">
  <div class="postTitle">
    <h1>Lorem</h1>
  </div>
  <div class="postInfo">Tags: <a onClick="sortPosts('lorem');">Lorem</a></div>
  <div class="postText">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.</div>
</div>

<div class="post ipsum dolar">
  <div class="postTitle">
    <h1>Ipsum dolar</h1>
  </div>
  <div class="postInfo">Tags: <a onClick="sortPosts('ipsum');">Ipsum</a> · <a onClick="sortPosts('dolar');">Dolar</a></div>
  <div class="postText">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.</div>
</div>

<div class="post dolar">
  <div class="postTitle">
    <h1>Dolar</h1>
  </div>
  <div class="postInfo">Tags: <a onClick="sortPosts('dolar');">Dolar</a></div>
  <div class="postText">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.</div>
</div>

CSS:

.post {
  width: 90%;
  padding: 5%;
  font-family: sans-serif;
}

.postInfo {
  font-style: italic;
  margin-bottom: 20px;
}

Javascript:

function sortPosts(tag) {
  if (document.getElementsByClassName('.post tag)')) {
    show();
  } else {
    hide();
  }
}

And all together in a fiddle

You have to use the following

var elements = document.getElementsByClassName('.post ' + tag );

Now if there were any elements matched, you will iterate over them and set their style.display properties to none.

Note: This could be far easier with jQuery ;-) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM