【问题标题】:show next item from array onclick in JavaScript在 JavaScript 中显示数组 onclick 中的下一项
【发布时间】:2020-04-20 18:30:34
【问题描述】:

有人可以向我解释如何显示 Array 中的元素吗?

我应该用什么来完成这个小的“推荐项目”。

目前,onclick 功能有效但不合适:
- 第二次点击后工作
- 仅显示来自 Array 的 2 个意见

<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;500&display=swap" rel="stylesheet">
<script src='https://kit.fontawesome.com/a076d05399.js'></script>
<script src='https://kit.fontawesome.com/a076d05399.js'></script>
<!--  I used AI generated faces from this website: https://www.thispersondoesnotexist.com/image  --> 
<body>
  <h3>CLIENT</h3>
    <h1>TESTIMONIALS</h1>
      <h5>Mercedes w124 coupe</h5>

        <div class="container" data-index="0">
          <div class="img" id="img"></div>
            <p class="name" id="names"></p>
            <p class="text" id="texts">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
            <i class='fas fa-quote-left' style='font-size:36px'></i>
            <button class="left"  onclick="next('left')"><i class='fas fa-angle-left'></i></button>
            <button class="right" onclick="next('right')"><i class='fas fa-angle-right'></i></button>
        </div>
</body>


var opinions = [
  { name: "Carol",
    text: "Roomy and hard wearing inside, solid build quality that disguises miles well, still has class especially in estate and coupe form",
    img:  "https://www.thispersondoesnotexist.com/image"
  },{ 
    name: "Alex",
    text: "Strong, reliable, comfortable, well-built, safe. Bigger, more modern car than W123.",
    img:  "https://www.thispersondoesnotexist.com/image"
  },{ 
    name: "Jordan",
    text: "Extremely good looking coupe and convertible, with nice pillarless side window arrangement,solid build quality that disguises miles well, good ones are still capable of turning heads",
    img:  "https://www.thispersondoesnotexist.com/image"
  }];

var element = document.getElementById("img");
var i = 0;
function next(direction) {
 if(direction === 'right'){
    element.style.backgroundImage  ="url('"+ opinions[i++].img +"')";
    document.getElementById("names").innerHTML = opinions[i].name;
    document.getElementById("texts").innerHTML =  opinions[i].text;
 } else {
    element.style.backgroundImage  ="url('"+ opinions[i--].img +"')";
    document.getElementById("names").innerHTML = opinions[i].name;
    document.getElementById("texts").innerHTML =  opinions[i].text;
    }
};

【问题讨论】:

    标签: javascript arrays function object onclick


    【解决方案1】:

    在检查数组是否包含该元素之前,您要增加 i 的值。

    还有,这条线

    opinions[i++].img
    

    您将在第一次点击时获得 options[1].img,因为您已将 i 定义为从 0 开始。

    检查如下:

    var opinions = [
      { name: "Carol",
        text: "Roomy and hard wearing inside, solid build quality that disguises miles well, still has class especially in estate and coupe form",
        img:  "https://www.thispersondoesnotexist.com/image"
      },{ 
        name: "Alex",
        text: "Strong, reliable, comfortable, well-built, safe. Bigger, more modern car than W123.",
        img:  "https://www.thispersondoesnotexist.com/image"
      },{ 
        name: "Jordan",
        text: "Extremely good looking coupe and convertible, with nice pillarless side window arrangement,solid build quality that disguises miles well, good ones are still capable of turning heads",
        img:  "https://www.thispersondoesnotexist.com/image"
      }];
    
    var element = document.getElementById("img");
    var i = -1; // start with negative value
    
    function next(direction) {
      if(direction === 'right') {
        if(opinions[i+1]) {  // check if element exists before incrementing i
          i++;
          element.style.backgroundImage  ="url('"+ opinions[i].img +"')";
          document.getElementById("names").innerHTML = opinions[i].name;
          document.getElementById("texts").innerHTML =  opinions[i].text;
        }
      } else {
        if(opinions[i-1]) {
          i--;
          element.style.backgroundImage  ="url('"+ opinions[i].img +"')";
          document.getElementById("names").innerHTML = opinions[i].name;
          document.getElementById("texts").innerHTML =  opinions[i].text;
        }
      }
    }
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;500&display=swap" rel="stylesheet">
    <script src='https://kit.fontawesome.com/a076d05399.js'></script>
    <script src='https://kit.fontawesome.com/a076d05399.js'></script>
    <!--  I used AI generated faces from this website: https://www.thispersondoesnotexist.com/image  --> 
    
    <h3>CLIENT</h3>
    <h1>TESTIMONIALS</h1>
    <h5>Mercedes w124 coupe</h5>
    
    <div class="container" data-index="0">
      <div class="img" id="img"></div>
        <p class="name" id="names"></p>
        <p class="text" id="texts">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
        <i class='fas fa-quote-left' style='font-size:36px'></i>
        <button class="left"  onclick="next('left')"><i class='fas fa-angle-left'></i></button>
        <button class="right" onclick="next('right')"><i class='fas fa-angle-right'></i></button>
    </div>

    【讨论】:

      【解决方案2】:

      您的计数器有点错误。我还建议在结束时重置计数器:

      var opinions = [
        { name: "Carol",
          text: "Roomy and hard wearing inside, solid build quality that disguises miles well, still has class especially in estate and coupe form",
          img:  "https://www.thispersondoesnotexist.com/image"
        },{ 
          name: "Alex",
          text: "Strong, reliable, comfortable, well-built, safe. Bigger, more modern car than W123.",
          img:  "https://www.thispersondoesnotexist.com/image"
        },{ 
          name: "Jordan",
          text: "Extremely good looking coupe and convertible, with nice pillarless side window arrangement,solid build quality that disguises miles well, good ones are still capable of turning heads",
          img:  "https://www.thispersondoesnotexist.com/image"
        }];
      
      var element = document.getElementById("img");
      var i = -1;
      function next(direction) {
       if(direction === 'right'){
          i = i < opinions.length - 1 ? i + 1 : 0
          element.style.backgroundImage  ="url('"+ opinions[i].img +"')";
          document.getElementById("names").innerHTML = opinions[i].name;
          document.getElementById("texts").innerHTML =  opinions[i].text;
       } else {
          i = i > 0 ? i - 1 : opinions.length - 1
          element.style.backgroundImage  ="url('"+ opinions[i].img +"')";
          document.getElementById("names").innerHTML = opinions[i].name;
          document.getElementById("texts").innerHTML =  opinions[i].text;
          }
      };
      <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;500&display=swap" rel="stylesheet">
      <script src='https://kit.fontawesome.com/a076d05399.js'></script>
      <script src='https://kit.fontawesome.com/a076d05399.js'></script>
      <h3>CLIENT</h3>
          <h1>TESTIMONIALS</h1>
            <h5>Mercedes w124 coupe</h5>
      
              <div class="container" data-index="0">
                <div class="img" id="img"></div>
                  <p class="name" id="names"></p>
                  <p class="text" id="texts">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
                  <i class='fas fa-quote-left' style='font-size:36px'></i>
                  <button class="left"  onclick="next('left')"><i class='fas fa-angle-left'></i>prev</button>
                  <button class="right" onclick="next('right')"><i class='fas fa-angle-right'></i>next</button>
              </div>

      【讨论】:

      • 非常感谢您解决了这个问题。你能像我 5 岁一样告诉我 -> 为什么你使用这行代码 ``` i = i
      • @KonradSzymanski :D 我会试试的。这称为 ternary operator 并用作内联 if 表达式。架构是myVariableToSet = myCondition ? myTrueCase : myFalseCase。所以我在那里写的也可以这样写:if (i &lt; opinions.length - 1) { i = i + 1 } else { i = 0 }。我希望这能澄清一点。这是一个 MDN 链接:developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
      【解决方案3】:

      我刚刚测试了它,它工作正常。关于“它只显示两个推荐”的行为,可能看起来是这样,因为在第一次加载时它不会自动显示第一个推荐,所以当你点击右时你只能前进到最后两个,但是如果你开始点击左您最终将能够到达第一个。

      我修改了您的代码以在页面加载时自动显示第一个推荐:

      	var i = -1;
      	var opinions = [
      	{ name: "Carol",
      		text: "Roomy and hard wearing inside, solid build quality that disguises miles well, still has class especially in estate and coupe form",
      		img:  "https://www.thispersondoesnotexist.com/image"
      	},{ 
      		name: "Alex",
      		text: "Strong, reliable, comfortable, well-built, safe. Bigger, more modern car than W123.",
      		img:  "https://www.thispersondoesnotexist.com/image"
      	},{ 
      		name: "Jordan",
      		text: "Extremely good looking coupe and convertible, with nice pillarless side window arrangement,solid build quality that disguises miles well, good ones are still capable of turning heads",
      		img:  "https://www.thispersondoesnotexist.com/image"
      	}];
      
      	function next(direction) {
      	var element = document.getElementById("img");
      	 if(direction === 'right'){
      	 i++;
      			if (element != undefined) element.style.backgroundImage  ="url('"+ opinions[i].img +"')";
      			document.getElementById("names").innerHTML = opinions[i].name;
      			document.getElementById("texts").innerHTML =  opinions[i].text;
      	 } else {
      	 i--;
      			if (element != undefined) element.style.backgroundImage  ="url('"+ opinions[i].img +"')";
      			document.getElementById("names").innerHTML = opinions[i].name;
      			document.getElementById("texts").innerHTML =  opinions[i].text;
      			}
      	};
      
      	(function() {
      		next('right');	 
      	})();
      <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;500&display=swap" rel="stylesheet">
      <script src='https://kit.fontawesome.com/a076d05399.js'></script>
      <script src='https://kit.fontawesome.com/a076d05399.js'></script>
      <!--  I used AI generated faces from this website: https://www.thispersondoesnotexist.com/image  --> 
      <body>
        <h3>CLIENT</h3>
          <h1>TESTIMONIALS</h1>
            <h5>Mercedes w124 coupe</h5>
      
              <div class="container" data-index="0">
                <div class="img" id="img"></div>
                  <p class="name" id="names"></p>
                  <p class="text" id="texts">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
                  <i class='fas fa-quote-left' style='font-size:36px'></i>
                  <button class="left"  onclick="next('left')"><i class='fas fa-angle-left'></i></button>
                  <button class="right" onclick="next('right')"><i class='fas fa-angle-right'></i></button>
              </div>
      </body>

      当数组为空以及点击超出索引时,您仍然需要处理。

      编辑:对索引 i 进行小幅调整。

      希望对你有帮助。

      【讨论】:

      • 如果这个答案也有帮助,请投票。谢谢。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-12
      • 1970-01-01
      • 2020-06-20
      • 1970-01-01
      • 2019-04-02
      相关资源
      最近更新 更多