首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Jquery单击多个ID并获取值。

Jquery单击多个ID并获取值。
EN

Stack Overflow用户
提问于 2018-05-13 08:13:29
回答 2查看 1.8K关注 0票数 1

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

代码语言:javascript
复制
<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

代码语言:javascript
复制
$(".heroes-pic").on("click", () => {
  player = $(this).attr("value");
  console.log(player);
});

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-05-13 08:17:07

您必须使用经典函数而不是箭头函数。this on箭头函数指的是单击的HTMLDocument和对象。这就是为什么你没有得到正确的结果。您正在从HTMLDocument获得更高的值。

代码语言:javascript
复制
$(".heroes-pic").on("click", function() {
  player = $(this).attr("value");
  console.log(player);
});
代码语言:javascript
复制
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="heroes-selection" class="row dflex justify-content-left">
  <figure id="luna" class="heroes-pic border text-danger m-3" value="heroes.luna"> heroes.luna
    <img class="animated-gif">
  </figure>

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

</div>

其他选项:您可以在箭头函数上使用event.currentTarget而不是this

比如:

代码语言:javascript
复制
$(".heroes-pic").on("click", (event) => {
  player = $(event.currentTarget).attr("value");
  console.log(player);
});
代码语言:javascript
复制
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<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">heroes.luna
  </figure>

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

</div>

票数 1
EN

Stack Overflow用户

发布于 2018-05-13 08:15:58

这是因为您使用的是一个箭头函数,它将this参数绑定到封闭范围的下面。

请参阅this

代之以下列功能:

代码语言:javascript
复制
$(".heroes-pic").on("click", function () {
  player = $(this).attr("value");
  console.log(player);
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50314087

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档