forEach不是函数

时间:2018-03-15 16:38:54

标签: javascript html css multidimensional-array

当输入值与数组中'fear'属性的值匹配时,我想过滤列表。但我一直得到zoeken.foreach不是函数的错误。

它会记录我的输入值,但每次输入内容时都会弹出错误。 我怀疑它与错误选择const zoeken = document.querySelector( ul );const $li = zoek.dataset.li; console.log($li.toUpperCase().indexOf(filter) > -1);有关,但我不确定。

我正在使用javascript。 感谢您的帮助!

{
  const phobias = [
      {
        name: `Arachnophobia`,
        defenition: `Arachnophobia is the fear of spiders and other arachnids. This phobia is quite common, affecting as many as 1 in 3 women and 1 in 4 men. The sight of a spider can trigger a fear response, but in some cases, simply an image of an arachnid or the thought of a spider can lead to feelings of overwhelming fear and panic.

        So why are so many people terrified of arachnids? While there are an estimated 35,000 different spider species, only around a dozen pose any type of real threat to humans. One of the most common explanations for this and similar animal phobias is that such creatures once posed a considerable threat to our ancestors who lacked the medical know-how and technological tools to address injuries from animals and insects. As a result, evolution contributed to a predisposition to fear these creatures.`,
        icon: `assets/spider.jpg`,
        fear: `spiders`,
      }, {
        name: `Ophidiophobia`,
        defenition: `Ophidiophobia is the fear of snakes. This phobia is quite common and often attributed to evolutionary causes, personal experiences, or cultural influences. Some suggest that since snakes are sometimes poisonous, our ancestors who avoided such dangers were more likely to survive and pass down their genes. In a study of 35 snake-fearful participants, however, researchers found that only 3 of these individuals had ever been bitten by a snake. In fact, the majority of the participants had little or no direct experiences with snakes in any capacity.

        Another theory suggests that the fear of snakes and similar animals might arise out an inherent fear of disease and contamination. Studies have shown that these animals tend to provoke a disgust response, which might explain why snake phobias are so common yet people tend not to exhibit similar phobias of dangerous animals such as lions or bears.`,
        icon: `assets/snake.jpg`,
        fear: `snakes`,
      }, {
        name: `Acrophobia`,
        defenition: `Acrophobia, or the fear of heights, impacts an estimated 23 million adults. This fear can lead to anxiety attacks and avoidance of high places. People who suffer from this phobia may go to great lengths to avoid high places such as bridges, towers, or tall buildings.

        While in some cases this fear of heights may be the result of a traumatic experience, current thinking suggests that this fear may have evolved as an adaptation to an environment in which a fall from heights posed a significant danger. While it is common for people to have some degree of fear when encountering heights, a phobia involves a severe fear that can result in panic attacks and avoidance behaviors.`,
        icon: `assets/height.jpg`,
        fear: `heights`,
      }, {
        name: `Aerophobia`,
        defenition: `Aerophobia, or the fear of flying, affects an estimated 8 million U.S. adults despite the fact that airplane accidents are actually very uncommon. Around 1 out of every 3 people has some level of fear of flying. Some of the common symptoms associated with this phobia include trembling, rapid heartbeat, and feeling disoriented.

        The fear of flying sometimes causes people to avoid flying altogether. It is often treated using exposure therapy, in which the client is gradually and progressively introduced to flying. The individual may start by simply imagining themselves on a plane before slowly working up to actually sitting on a plane and finally sitting through a flight.`,
        icon: `assets/plane.jpg`,
        fear: `flying`,
      }, {
        name: `Cynophobia`,
        defenition: `Cynophobia, or the fear of dogs, is often associated with specific personal experiences such as being bitten by a dog during childhood. Such events can be quite traumatic and can lead to fear responses that last well into adulthood.

        This particular phobia can be quite common. Some estimates suggest that as many as 36 percent of all individuals who seek treatment for a specific phobia have this severe fear of dogs.

        This phobia is not just a normal apprehension of unfamiliar canines; it is an irrational and excessive fear that can have a serious impact on a person's life and functioning. For example, a person with this phobia might feel unable to walk down a certain street because they know that there is a dog living in that neighborhood. This avoidance can impact the individual's ability to function in their daily life and make it difficult to get to work, school, or other events outside of the home.`,
        icon: `assets/dog.jpg`,
        fear: `dogs`,
      }, {
        name: `Astraphobia`,
        defenition: `Astraphobia is a fear of thunder and lightning. People with this phobia experience overwhelming feelings of fear when they encounter such weather-related phenomena.

        Symptoms of astraphobia are often similar to those of other phobias and include shaking, rapid heart rate, and increased respiration. During a thunder or lightning storm, people with this disorder may go to great lengths to take shelter or hide from the weather event such as hiding in bed under the covers or even ducking inside a closet or bathroom.

        People with this phobia also tend to develop an excessive preoccupation with the weather. They may spend a great deal of time each day tracking the local and national weather in order to know when any type of storm might take place. In some instances, this phobia may even lead to agoraphobia in which people are so afraid of encountering lightning or thunder that they are unable to leave their homes.`,
        icon: `assets/lightning.jpg`,
        fear: `lightning`,
      }, {
        name: `Trypanophobia`,
        defenition: `Trypanophobia is the fear of injections, a condition that can sometimes cause people to avoid medical treatments and doctors. Like many phobias, this fear often goes untreated because people avoid the triggering object and situation. Estimates suggest that as many as 10 ​percent of people in the U.S. are affected by this type of phobia.

        When people with this phobia do have to have an injection, they may experience feelings of extreme dread and elevated heart rate leading up to the procedure. Some people even pass out during the injection. Because these symptoms can be so distressing, people with this phobia sometimes avoid doctors, dentists, and other medical professionals even when they have some type of physical or dental ailment that needs attention.`,
        icon: `assets/injection.jpg`,
        fear: `injections`,
      }, {
        name: `Social Phobia`,
        defenition: `Social phobia involves the fear of social situations and can be quite debilitating. In many cases, these phobias can become so severe that people avoid events, places, and people who are likely to trigger an anxiety attack.

        People with this phobia fear being watched or humiliated in front of others. Even ordinary, everyday tasks such as eating a meal can be anxiety-provoking. The American Psychiatric Association reports that social phobias often develop during puberty and can last throughout life unless they are treated.

        The most common form of social phobia is a fear of public speaking. In some cases, social phobias can cause people to avoid social situations including school and work, which can have a major impact on the individual's well-being and ability to function.`,
        icon: `assets/social.jpg`,
        fear: `social situations`,
      }, {
        name: `Claustrophobia`,
        defenition: `Nearly 5 to 7% of the world’s population is known to suffer from Claustrophobia – the fear of small or restricted spaces. This phobia is mainly related to the fear of suffocation or the fear of restriction. The phobia has been highly studied by experts and scientists, though the sad fact remains that only 2% of its sufferers seek treatment. Claustrophobia is often confused with Cleithrophobia which is the extreme fear of being trapped.`,
        icon: `assets/small.jpg`,
        fear: `small rooms`,
      }, {
        name: `Mysophobia`,
        defenition: `Mysophobia, or the excessive fear of germs and dirt, can lead people to engage in extreme cleaning, compulsive hand-washing, and even avoidance of things of situations perceived as dirty. In some instances, this phobia may be related to obsessive-compulsive disorder.

        This common phobia can also result in people avoiding physical contact with other people out of fear of contamination, overuse of disinfectants, and excessive preoccupation with media reports about illness outbreaks. People with this phobia may also avoid areas where germs are more likely to be present such as doctor's offices, airplanes, schools, and pharmacies.`,
        icon: `assets/dirt.jpg`,
        fear: `bacteria`,
      }
    ];

    const createListItems = phobias => {
      const $ul = document.querySelector(`ul`);
      const input = document.querySelector(`input`);
      for (var i = 0; i < phobias.length; i++) {
        const $li = document.createElement(`li`);
        $li.textContent = phobias[i].name;
        $li.dataset.index = i;
        $ul.appendChild($li);
        $li.addEventListener(`mouseover`, handleMouseoverListitem);
        input.addEventListener(`keyup`, handleKeyUpSearch);
      }
    };

    const handleMouseoverListitem = e => {
      const $imgs = document.querySelectorAll(`.fobia`);
      const $li = e.currentTarget;
      const index = $li.dataset.index;
      $imgs.forEach($img => {
        $img.src = phobias[index].icon;
      });
      const $p = document.querySelector(`p`);
      $p.textContent = phobias[index].defenition;
    };

    const handleKeyUpSearch = () => {
      const input = document.querySelector(`input`);
      const filter = input.value.toUpperCase();
      const $ul = document.querySelector(`ul`);
      const zoeken = document.querySelectorAll(`li`);
      zoeken.forEach(zoek => {
        const fear = zoek.dataset.fear;
        console.log(fear.toUpperCase().indexOf(filter) > -1);
        if(fear.toUpperCase().indexOf(filter) > -1) {
          zoek.classList.remove(`hide`);
        } else {
          zoek.classList.add(`hide`);
        }
      });
    };

    const init = () => {
      createListItems(phobias);
    };

    init();
}
html {
  box-sizing: border-box;
  height: 100%;
  font-size: 62.5%;
}

*, *:before, *:after {
  box-sizing: inherit;
}

body{
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;

  font-family: sans-serif;
}

.spider{
  background-image: url(../assets/0.jpg);
  background-size: cover;
}

h1{
  font-size: 5rem;
  border-bottom: .5rem solid black;
  margin-top: 1rem;
  margin-bottom: 1.7rem;
}

ul{
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  margin-bottom: 3rem;
}

li{
  font-size: 2.5rem;
  padding: .5rem;
  background-color: rgba(255,255,255,0.7);
  cursor: pointer;
  border: .1rem solid black;
  width: 20rem;
  margin-bottom: .5rem;
  text-align: center;
  background-color: crimson;
}

p{
  text-align: center;
  background-color: rgba(255,255,255,0.7);
  max-width: 75rem;
  font-size: 1.8rem;
  margin-bottom: 2rem;
}

img{
  height: 30rem;
}

div{
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  align-items: center;
  width: 100vw;
}

input{
  margin-bottom: 2rem;
  padding: 0.5rem;
  font-size: 1.7rem;
}

.hide{
  display: none;
}
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Phobias || Devine</title>
    <link rel="stylesheet" href="css/reset.css">
    <link rel="stylesheet" href="css/style.css">
  </head>
  <body>
    <h1>The most common phobias</h1>
    <input type="text" id="fear" placeholder="What are you afraid of?">
    <div>
      <img class="fobia" src="#" alt="">
      <ul></ul>
      <img class="fobia" src="#" alt="">
    </div>
      <p></p>
    <script src="js/script.js"></script>
  </body>
</html>

2 个答案:

答案 0 :(得分:0)

我认为最重要的是你应该使用.querySelectorAll(ul)来获取一个数组。我已将handleKeyUpSearch函数修改为如下所示:

const handleKeyUpSearch = () => { const input = document.querySelector(`input`); console.log(input.value); const filter = input.value.toUpperCase(); const zoeken = document.querySelectorAll(`ul`); zoeken.forEach(zoek => { const $lis = zoek.getElementsByTagName(`li`); for (var i = 0; i < $lis.length; i++) { const title = $lis[i].innerText || $lis[i].textContent; if(title.toUpperCase().indexOf(filter) > -1){ zoek.classList.remove(`hide`); } else{ zoek.classList.add(`hide`); } } }); } 我不确定这种行为是否符合您的要求,但它会让您通过错误消息。

&#13;
&#13;
{
  const phobias = [
      {
        name: `Arachnophobia`,
        defenition: `Arachnophobia is the fear of spiders and other arachnids. This phobia is quite common, affecting as many as 1 in 3 women and 1 in 4 men. The sight of a spider can trigger a fear response, but in some cases, simply an image of an arachnid or the thought of a spider can lead to feelings of overwhelming fear and panic.

        So why are so many people terrified of arachnids? While there are an estimated 35,000 different spider species, only around a dozen pose any type of real threat to humans. One of the most common explanations for this and similar animal phobias is that such creatures once posed a considerable threat to our ancestors who lacked the medical know-how and technological tools to address injuries from animals and insects. As a result, evolution contributed to a predisposition to fear these creatures.`,
        icon: `assets/spider.jpg`,
        fear: `spiders`,
      }, {
        name: `Ophidiophobia`,
        defenition: `Ophidiophobia is the fear of snakes. This phobia is quite common and often attributed to evolutionary causes, personal experiences, or cultural influences. Some suggest that since snakes are sometimes poisonous, our ancestors who avoided such dangers were more likely to survive and pass down their genes. In a study of 35 snake-fearful participants, however, researchers found that only 3 of these individuals had ever been bitten by a snake. In fact, the majority of the participants had little or no direct experiences with snakes in any capacity.

        Another theory suggests that the fear of snakes and similar animals might arise out an inherent fear of disease and contamination. Studies have shown that these animals tend to provoke a disgust response, which might explain why snake phobias are so common yet people tend not to exhibit similar phobias of dangerous animals such as lions or bears.`,
        icon: `assets/snake.jpg`,
        fear: `snakes`,
      }, {
        name: `Acrophobia`,
        defenition: `Acrophobia, or the fear of heights, impacts an estimated 23 million adults. This fear can lead to anxiety attacks and avoidance of high places. People who suffer from this phobia may go to great lengths to avoid high places such as bridges, towers, or tall buildings.

        While in some cases this fear of heights may be the result of a traumatic experience, current thinking suggests that this fear may have evolved as an adaptation to an environment in which a fall from heights posed a significant danger. While it is common for people to have some degree of fear when encountering heights, a phobia involves a severe fear that can result in panic attacks and avoidance behaviors.`,
        icon: `assets/height.jpg`,
        fear: `heights`,
      }, {
        name: `Aerophobia`,
        defenition: `Aerophobia, or the fear of flying, affects an estimated 8 million U.S. adults despite the fact that airplane accidents are actually very uncommon. Around 1 out of every 3 people has some level of fear of flying. Some of the common symptoms associated with this phobia include trembling, rapid heartbeat, and feeling disoriented.

        The fear of flying sometimes causes people to avoid flying altogether. It is often treated using exposure therapy, in which the client is gradually and progressively introduced to flying. The individual may start by simply imagining themselves on a plane before slowly working up to actually sitting on a plane and finally sitting through a flight.`,
        icon: `assets/plane.jpg`,
        fear: `flying`,
      }, {
        name: `Cynophobia`,
        defenition: `Cynophobia, or the fear of dogs, is often associated with specific personal experiences such as being bitten by a dog during childhood. Such events can be quite traumatic and can lead to fear responses that last well into adulthood.

        This particular phobia can be quite common. Some estimates suggest that as many as 36 percent of all individuals who seek treatment for a specific phobia have this severe fear of dogs.

        This phobia is not just a normal apprehension of unfamiliar canines; it is an irrational and excessive fear that can have a serious impact on a person's life and functioning. For example, a person with this phobia might feel unable to walk down a certain street because they know that there is a dog living in that neighborhood. This avoidance can impact the individual's ability to function in their daily life and make it difficult to get to work, school, or other events outside of the home.`,
        icon: `assets/dog.jpg`,
        fear: `dogs`,
      }, {
        name: `Astraphobia`,
        defenition: `Astraphobia is a fear of thunder and lightning. People with this phobia experience overwhelming feelings of fear when they encounter such weather-related phenomena.

        Symptoms of astraphobia are often similar to those of other phobias and include shaking, rapid heart rate, and increased respiration. During a thunder or lightning storm, people with this disorder may go to great lengths to take shelter or hide from the weather event such as hiding in bed under the covers or even ducking inside a closet or bathroom.

        People with this phobia also tend to develop an excessive preoccupation with the weather. They may spend a great deal of time each day tracking the local and national weather in order to know when any type of storm might take place. In some instances, this phobia may even lead to agoraphobia in which people are so afraid of encountering lightning or thunder that they are unable to leave their homes.`,
        icon: `assets/lightning.jpg`,
        fear: `lightning`,
      }, {
        name: `Trypanophobia`,
        defenition: `Trypanophobia is the fear of injections, a condition that can sometimes cause people to avoid medical treatments and doctors. Like many phobias, this fear often goes untreated because people avoid the triggering object and situation. Estimates suggest that as many as 10 ​percent of people in the U.S. are affected by this type of phobia.

        When people with this phobia do have to have an injection, they may experience feelings of extreme dread and elevated heart rate leading up to the procedure. Some people even pass out during the injection. Because these symptoms can be so distressing, people with this phobia sometimes avoid doctors, dentists, and other medical professionals even when they have some type of physical or dental ailment that needs attention.`,
        icon: `assets/injection.jpg`,
        fear: `injections`,
      }, {
        name: `Social Phobia`,
        defenition: `Social phobia involves the fear of social situations and can be quite debilitating. In many cases, these phobias can become so severe that people avoid events, places, and people who are likely to trigger an anxiety attack.

        People with this phobia fear being watched or humiliated in front of others. Even ordinary, everyday tasks such as eating a meal can be anxiety-provoking. The American Psychiatric Association reports that social phobias often develop during puberty and can last throughout life unless they are treated.

        The most common form of social phobia is a fear of public speaking. In some cases, social phobias can cause people to avoid social situations including school and work, which can have a major impact on the individual's well-being and ability to function.`,
        icon: `assets/social.jpg`,
        fear: `social situations`,
      }, {
        name: `Claustrophobia`,
        defenition: `Nearly 5 to 7% of the world’s population is known to suffer from Claustrophobia – the fear of small or restricted spaces. This phobia is mainly related to the fear of suffocation or the fear of restriction. The phobia has been highly studied by experts and scientists, though the sad fact remains that only 2% of its sufferers seek treatment. Claustrophobia is often confused with Cleithrophobia which is the extreme fear of being trapped.`,
        icon: `assets/small.jpg`,
        fear: `small rooms`,
      }, {
        name: `Mysophobia`,
        defenition: `Mysophobia, or the excessive fear of germs and dirt, can lead people to engage in extreme cleaning, compulsive hand-washing, and even avoidance of things of situations perceived as dirty. In some instances, this phobia may be related to obsessive-compulsive disorder.

        This common phobia can also result in people avoiding physical contact with other people out of fear of contamination, overuse of disinfectants, and excessive preoccupation with media reports about illness outbreaks. People with this phobia may also avoid areas where germs are more likely to be present such as doctor's offices, airplanes, schools, and pharmacies.`,
        icon: `assets/dirt.jpg`,
        fear: `bacteria`,
      }
    ];

    const createListItems = phobias => {
      const $ul = document.querySelector(`ul`);
      const input = document.querySelector(`input`);
      for (var i = 0; i < phobias.length; i++) {
        const $li = document.createElement(`li`);
        $li.textContent = phobias[i].name;
        $li.dataset.index = i;
        $li.dataset.fear = phobias[i].fear;
        $ul.appendChild($li);
        $li.addEventListener(`mouseover`, handleMouseoverListitem);
        input.addEventListener(`keyup`, handleKeyUpSearch);
      }
    };

    const handleMouseoverListitem = e => {
      const $imgs = document.querySelectorAll(`.fobia`);
      const $li = e.currentTarget;
      const index = $li.dataset.index;
      $imgs.forEach($img => {
        $img.src = phobias[index].icon;
      });
      const $p = document.querySelector(`p`);
      $p.textContent = phobias[index].defenition;
    };

    const handleKeyUpSearch = () => {
      var input = document.querySelector(`input`);
      
      var filter = input.value.toUpperCase();
console.log(filter)
      const zoeken = document.querySelectorAll(`ul`);
      zoeken.forEach(zoek => {
        const $lis = zoek.getElementsByTagName(`li`);
        for (var i = 0; i < $lis.length; i++) {
          var title = $lis[i].dataset.fear;
          if(title.toUpperCase().indexOf(filter) > -1){
            $lis[i].classList.remove(`hide`);
          } else{
            $lis[i].classList.add(`hide`);
          }
        }
      });
    }


    const filterFears = () => {

    }

    const init = () => {
      createListItems(phobias);
    };

    init();
}
&#13;
html {
  box-sizing: border-box;
  height: 100%;
  font-size: 62.5%;
}

*, *:before, *:after {
  box-sizing: inherit;
}

body{
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;

  font-family: sans-serif;
}

.spider{
  background-image: url(../assets/0.jpg);
  background-size: cover;
}

h1{
  font-size: 5rem;
  border-bottom: .5rem solid black;
  margin-top: 1rem;
  margin-bottom: 1.7rem;
}

ul{
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  margin-bottom: 3rem;
}

li{
  font-size: 2.5rem;
  padding: .5rem;
  background-color: rgba(255,255,255,0.7);
  cursor: pointer;
  border: .1rem solid black;
  width: 20rem;
  margin-bottom: .5rem;
  text-align: center;
  background-color: crimson;
}

p{
  text-align: center;
  background-color: rgba(255,255,255,0.7);
  max-width: 75rem;
  font-size: 1.8rem;
  margin-bottom: 2rem;
}

img{
  height: 30rem;
}

div{
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  align-items: center;
  width: 100vw;
}

input{
  margin-bottom: 2rem;
  padding: 0.5rem;
  font-size: 1.7rem;
}

.hide{
  display: none;
}
&#13;
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Phobias || Devine</title>
    <link rel="stylesheet" href="css/reset.css">
    <link rel="stylesheet" href="css/style.css">
  </head>
  <body>
    <h1>The most common phobias</h1>
    <input type="text" id="fear" placeholder="What are you afraid of?">
    <div>
      <img class="fobia" src="#" alt="">
      <ul></ul>
      <img class="fobia" src="#" alt="">
    </div>
      <p></p>
    <script src="js/script.js"></script>
  </body>
</html>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

以下行只会返回&#34; ul&#34;元件。你不能直接迭代这个。

const zoeken = document.querySelector(`ul`);

您需要执行以下操作来迭代此<li>的每个<ul>

const zoeken = document.querySelectorAll(`ul > li`);

querySelectorAll将返回一个NodeList对象,允许您遍历li。请注意,此选择器最好更合格(使用<ul>的ID或类),但适用于您提供的html。