[英]How to use a variable in innerHTML statement to display specific object values
我有从按钮传递到HTML文件中的函数go()的变量。 然后,函数go()调用外部函数displayInfo()并将变量传递给它。
下面的代码显示“未定义”。 是否可以使用countryName字符串定位对象而不是对象名称?
document.getElementById("show-country").innerHTML = countryName.name;
document.getElementById("show-population").innerHTML = countryName.population;
index.html:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
</head>
<body>
<script>
function go(val)
{ displayInfo(val); }
</script>
<input type="button" value="england" onclick="go(this.value)">
<input type="button" value="france" onclick="go(this.value)">
<div>
<h1 id="show-country"></h1>
<p id="show-population"></p>
</div>
<script src="countries.js" type="text/javascript"></script>
</body>
</html>
country.js:
function displayInfo (countryName)
{
var england =
{
name : "England",
population: "53.01 million"
};
var france =
{
name : "France",
population: "66.9 million"
};
document.getElementById("show-country").innerHTML = countryName.name;
document.getElementById("show-population").innerHTML = countryName.population;
}
您目前的处理方式,不。 您可以将国家/地区存储在一个对象中,然后定位对象键:
let countries = {
england: {
name : "England",
population: "53.01 million"
},
france: {
name : "France",
population: "66.9 million"
}
}
然后使用括号表示法显示属性(如果存在):
if (countries.hasOwnProperty(countryName)) {
document.getElementById("show-country").innerHTML = countries[countryName].name;
document.getElementById("show-population").innerHTML = countries[countryName].population;
}
这是一个可能对您有帮助的例子
var countries={ england :{ name : "England", population: "53.01 million" }, france:{ name : "France", population: "66.9 million" } }; function displayInfo (countryName){ document.getElementById("show-country").innerHTML = countries[countryName].name; document.getElementById("show-population").innerHTML = countries[countryName].population; }
<!doctype html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> </head> <body> <script> function go(val) { displayInfo(val); } </script> <input type="button" value="england" onclick="go(this.value)"> <input type="button" value="france" onclick="go(this.value)"> <div> <h1 id="show-country"></h1> <p id="show-population"></p> </div> <script src="countries.js" type="text/javascript"></script> </body> </html>
在countryName中,您只需传递按钮的值属性。 在javascript函数中,您使用countryName.name或人口,但是countryName只是一个字符串。
解决方案是:
function displayInfo (countryName) { var data = null; var england = { name : "England", population: "53.01 million" }; var france = { name : "France", population: "66.9 million" };
if(countryName === "england"){ data = england; } else{ data = france; } document.getElementById("show-country").innerHTML = data.name; document.getElementById("show-population").innerHTML = data.population;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.