我的老师让我们对创建一个完全替换数组内对象中的段落和单词的函数的语法感到困惑。
她也没有解释换行符语法以及如何正确连接换行符字符串。
我的函数语法做错了什么?
为什么我们使用函数而不使用警报?
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>
最佳答案
答案:
- 您的按钮具有
states
标识符,不是scinfo
- 将按钮更改为
document.getElementById("states")
不document.getElementById("scinfo")
,因为该 ID 不存在。
- 将按钮更改为
- 您需要使用正确的索引。
- 您指向数组
states.eachstate
,但提供了零索引( [0] ),该索引查看第一个元素。 - 南卡罗来纳州信息位于第二项中,其索引为一。 ( [1] )
- 您指向数组
- 您需要提供与数据相关的大小写正确的
属性
名称。这些区分大小写states.eachstate[1].population
与states.eachstate[1].Population
不同
- 您需要提供正确属性名称。
- 当数据中的
states.eachstate[0].StateBird
列出时,您可以使用states.eachstate[0].bird
- 当数据中的
示例:
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>
关于javascript - 单击按钮时更改文本的正确函数语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58276129/