Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
120 views
in Technique[技术] by (71.8m points)

javascript - Filtering based on state items

So i have this array as my state:

["item-one","item-two", "item-three"]

Now i have these items on my webpage:

Item One
Item Two
Item Three
Item Four
Item Five

How can i filter these items based on the state of my array. So when i filter i would get the three first items? The html of the items are like so.

    <div>
      <label htmlFor="item-one">Item One</label>
      <input type="checkbox" name="" id="item-one"/>
    </div>
    <div>
      <label htmlFor="item-two">Item Two</label>
      <input type="checkbox" name="" id="item-two"/>
    </div>
    <div>
      <label htmlFor="item-three">Item Three</label>
      <input type="checkbox" name="" id="item-three"/>
    </div>
    <div>
      <label htmlFor="item-four">Item Four</label>
      <input type="checkbox" name="" id="item-four"/>
    </div>
    <div>
      <label htmlFor="item-five">Item Five</label>
      <input type="checkbox" name="" id="item-five"/>
    </div>

should i use a map function or what is the best approach?

question from:https://stackoverflow.com/questions/65843871/filtering-based-on-state-items

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You would need a reference to those elements on the page. From there, in you're render function you would show/hide those elements based on you're state.

Example:

// Assume `this.state` references you're array

const items = document.querySelector("div");
items.forEach(function (item) {
  const input_elm = item.querySelector("input");
  if (this.state.includes(input_elm.id)) {
    item.style.display = "block";
  } else {
    item.style.display = "none";
  }
});

Note: there are other ways to implement this. But I found this to be the simplest.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...