我制作了 5 个按钮、一个包含国家/地区名称的数组对象和一个空段落。
我希望段落的innerHTML根据我实现的for循环的索引显示对应的名称,这样,如果我单击第一个按钮,段落就会显示数组中的第一个国家,依此类推。但我在控制台中出现此错误:
Cannot read property 'country' of undefined
这是 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>
关于javascript - 无法正确运行js对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53324743/