首页 > 解决方案 > jQuery单击多个ID并获取值

问题描述

当用户单击它时,我试图获取元素的值。这是我的代码:

<div id="heroes-selection" class="row dflex justify-content-left">
    <figure id="luna" class="heroes-pic border text-danger m-3" value="heroes.luna">
      <img class="animated-gif">
   </figure>

   <figure id="qop" class="heroes-pic border text-danger m-3" value="heroes.qop">
      <img class="animated-gif">
   </figure>
</div>

我尝试使用 Jquery $(this),结果显示为undefined.

$(".heroes-pic").on("click", () => {
  player = $(this).attr("value");
  console.log(player);
});

我的目标是heroes.luna在用户单击带有id="luna". 同样的id="qop",我需要得到值heroes.qop。谢谢!

标签: javascriptjqueryonclickthis

解决方案


this这是因为您正在使用将参数绑定到封闭范围的 this的箭头函数。

请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#No_separate_this

用一个函数替换它:

$(".heroes-pic").on("click", function () {
  player = $(this).attr("value");
  console.log(player);
}

推荐阅读