首页 > 解决方案 > 单击按钮时更改文本的正确函数语法

问题描述

我的导师在语法上让我们感到困惑,以创建一个完全替换数组内对象中的段落和单词的函数。

她也没有解释换行符语法以及如何正确连接换行符字符串。

我在函数语法中做错了什么?

为什么我们使用一个函数而不是警报?

var button = document.getElementById("scinfo");
var states = {
  "eachstate": [{
      "Name": "North Carolina",
      "Capital": "Raleigh",
      "Population": "986,000",
      "StateBird": "Who Cares"

    },

    {
      "Name": "South Carolina",
      "Capital": "Columbia",
      "Population": "886,000",
      "StateBird": "Hawk"

    },


    {
      "Name": "Florida",
      "Capital": "Tallahasee",
      "Population": "975,000",
      "StateBird": "Flamingo"
    },

  ]
};

button.addEventListener("click", writestates, false);

function writestates() {
  document.getElementById("StateInfo").innerHTML = "<p>Name: " + states.eachstate[0].name + "</p>" + "<p>" + "Capital: " +
    states.eachstate[0].capital + "</p>" + "<p>" + "Bird: " + states.eachstate[0].bird + "</p>" + "<p>" + "Population: " +
    states.eachstate[0].population + "</p>"
}
<!-- Create a button to write out ONLY SC information when clicked -->
<button id="states" type="button">SC Information</button>

<div class="showstate">
  <h1>
    South Carolina
  </h1>

  <p id="StateInfo">
    This is where the new information should show up!
  </p>
</div>

标签: javascripthtmlarraysjsonfunction

解决方案


回答:

  • 您的按钮的标识符为states而不是 scinfo
    • 将按钮更改为document.getElementById("states") not document.getElementById("scinfo"),因为该 ID不存在
  • 您需要使用正确的索引
    • 您指向数组states.eachstate,但提供了查看第一项的零索引( [0] )。
    • 南卡罗来纳州信息在第二项中,其索引为1。( [1] )
  • 您需要提供与数据property相关的大小写正确的名称。这些是区分大小写的
    • states.eachstate[1].population 一样states.eachstate[1].Population
  • 您需要提供正确的属性名称。
    • 您在数据中使用states.eachstate[0].bird时将其列为states.eachstate[0].StateBird

例子:

var button = document.getElementById("states");
var states = {


    "eachstate": [
        {
        "Name":"North Carolina",
        "Capital": "Raleigh",
        "Population": "986,000",
        "StateBird": "Who Cares"

    },

        {
        "Name": "South Carolina",
        "Capital": "Columbia",
        "Population": "886,000",
        "StateBird": "Hawk"

    },


        {
        "Name": "Florida",
        "Capital": "Tallahasee",
        "Population": "975,000",
        "StateBird": "Flamingo"
            },

    ]
};

button.addEventListener("click", writestates, false);
function writestates()
{
    document.getElementById("StateInfo").innerHTML = "<p>Name: " + states.eachstate[1].Name + "</p>" + "<p>" + "Capital: "
        + states.eachstate[1].Capital + "</p>" + "<p>" + "Bird: " + states.eachstate[1].StateBird + "</p>" + "<p>" + "Population: " +
        states.eachstate[1].Population + "</p>"
}
<button id="states" type="button">SC Information</button>

<div class="showstate" >
    <h1>
        South Carolina
    </h1>

    <p id="StateInfo">
        This is where the new information should show up!
    </p>
</div>


推荐阅读