首页 > 解决方案 > 无法正确运行 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)
  })
}

拜托,谁能帮我弄清楚是什么问题?

谢谢

标签: javascriptjqueryarrays

解决方案


您不需要使用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>


推荐阅读