如何在使用JavaScript单击按钮时更改段落标记的内容

时间:2018-05-11 06:31:50

标签: javascript html

我想要这样的东西 我爱披萨

我喜欢豆子

我爱Tacos

我爱鱼

我爱鸡

这是我的代码,它只是印刷我爱鸡:

{{1}}

3 个答案:

答案 0 :(得分:2)

您也可以这样做



function displayFood() {
  var food = ["Pizza", "Beans", "Tacos", "Fish", "Chicken"];
  var text = '';
  food.forEach(function(el){
  	document.getElementById("food").innerHTML = text+= 'I love ' + el + '</br>';
  });

}

//document.querySelector('.show').addEventListener('click', displayFood);
&#13;
<button class="show" onClick="displayFood()">Show Food</button>
<p id="food"></p>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

只需进行一些修改即可。

您需要为text分配一个初始值,如var text = ""(空字符串)。

然后你需要移动document.getElementById("food").innerHTML = text; 在循环之外,所以你不要每次都覆盖它(或者你可以使用+=代替=并将其保留在循环内。

最后,您可以将i的声明移到循环标题中,我建议使用letconst关键字来声明变量而不是var

function displayFood() {
    let text = ""; // give it an initial value
    const food = ["Pizza", "Beans", "Tacos", "Fish", "Chicken"];
    for(let i = 0; i < food.length; i++) {
        text += "I love " + food[i] + "<br>";
    }
    // move the assignment outside of loop
    document.getElementById("food").innerHTML = text;
}
<button onclick="displayFood()">Show Food</button>
<p id="food"></p>

您甚至不需要显式循环来完成此任务。你所需要的只是Array.prototype.reduce然后你可以做这样的事情。

function displayFood() {
  const food = ["Pizza", "Beans", "Tacos", "Fish", "Chicken"];
  document.getElementById("food").innerHTML = food.reduce((acc, v) => acc + "I love " + v + "<br>", "");
}
<button onclick="displayFood()">Show Food</button>
<p id="food"></p>

答案 2 :(得分:1)

<!DOCTYPE html>
<html>
<head>

</head>
<body>
<button onclick="displayFood()">Show Food</button>
    <p id="food"></p>


 <script>
     
    function displayFood() {
        
           var text = ""; //asign empty string to text
           var food = ["Pizza", "Beans", "Tacos", "Fish", "Chicken"];
           var i;
           for(i = 0; i <food.length;i++) {
               text += "I love " + food[i] + "<br>";
               document.getElementById("food").innerHTML = text;

           }

       }
       /* This will output as follows: 
       
       I love Pizza
       I love Beans
       I love Tacos
       I love Fish
       I love Chicken
       
       */

</script>

这是正确的代码

<!DOCTYPE html>
<html>
<head>

</head>
<body>
<button onclick="displayFood()">Show Food</button>
    <p id="food"></p>


 <script>
     
    function displayFood() {
        
           var text = ""; //asign empty string to text
           var food = ["Pizza", "Beans", "Tacos", "Fish", "Chicken"];
           var i;
           for(i = 0; i <food.length;i++) {
               text += "I love " + food[i] + "<br>";
               document.getElementById("food").innerHTML = text;

           }

       }

</script>