javascript - 无法正确运行 js 对象
问题描述
我制作了 5 个按钮、一个包含国家名称的数组对象和一个空段落。
我希望段落的 innerHTML 根据我实现的 for 循环的索引显示对应的名称,这样如果我单击第一个按钮,段落将显示数组中的第一个国家,依此类推。但是我在控制台中出现了这个错误:
无法读取未定义的属性“国家/地区”
这是html:
<p id="par"></p>
<button class="but" id="1">1</button>
<button class="but" id="2">2</button>
<button class="but" id="3">3</button>
<button class="but" id="4">4</button>
<button class="but" id="5">5</button>
这是js:
var bArr = $(".but")
var paises = [
{country: "India", growth: 35},
{country: "Indonesia",growth: 30},
{country: "Russia",growth: 25},
{country: "Mars",growth: 20},
{country: "Pluton",growth: 15}
]
for (i = 0; i< bArr.length; i++){
$(bArr[i]).click(function(){
$("#par").html(paises[i].country)
})
}
拜托,谁能帮我弄清楚是什么问题?
谢谢
解决方案
您不需要使用for
循环。为所有按钮添加一个单击事件侦听器,并在事件处理程序中获取id
单击按钮的属性并使用它来选择数组的相关项。
var paises = [
{country: "India", growth: 35},
{country: "Indonesia",growth: 30},
{country: "Russia",growth: 25},
{country: "Mars",growth: 20},
{country: "Pluton",growth: 15}
];
$(".but").click(function(){
$("#par").text(paises[this.id-1].country);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="par"></p>
<button class="but" id="1">1</button>
<button class="but" id="2">2</button>
<button class="but" id="3">3</button>
<button class="but" id="4">4</button>
<button class="but" id="5">5</button>
推荐阅读
- python - Django ImageField 在处理时保持原始图像比例
- amazon-dynamodb - DynamoDB 中的并发更新,是否有任何保证?
- php - 如何对齐不同尺寸的图像
- webpack-encore - 使用 webpack-encore 复制文件
- jackson - 将成功反序列化为 Instant 的默认字符串格式?
- mysql - Mysql删除查询忘记了Id约束
- javascript - 如何将所有值的总和添加为 Chart.Js 中圆环图的图表标题?
- r - 替换R中csv文件中列中的几个字符
- python-3.x - AttributeError:模块“资源”没有属性“getpagesize”
- php - 检查一个多边形是否在 PHP 中的另一个多边形内