javascript - 单击按钮时更改文本的正确函数语法
问题描述
我的导师在语法上让我们感到困惑,以创建一个完全替换数组内对象中的段落和单词的函数。
她也没有解释换行符语法以及如何正确连接换行符字符串。
我在函数语法中做错了什么?
为什么我们使用一个函数而不是警报?
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")
notdocument.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>
推荐阅读
- javascript - 反应状态变化不会导致重新渲染
- angular - Angular 4+ 将带有其他一些数据的文件上传到 .NET Core Web API
- powershell - 使用 Outlook 2016 打开 .msg 文件?
- node.js - 无法获取 google api 的刷新令牌。节点js
- linux-kernel - 在Linux内核上,例如atomic_inc,atomic_dec等的原子操作可以保护多核环境下的变量吗?
- python - 如何使用嵌套列表通过 Python 格式化乘法表?
- amazon-web-services - Config 中的 AWS lambda-function-public-access-prohibited 规则
- string - 使用列表推导,将递增整数插入包含字符串的列表列表中
- c# - 在 Unity 中限制加速器的移动区域
- c++ - 使用堆栈时收到断言失败