当用户单击元素时,我试图获取元素的值。这是我的密码:
<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。谢谢!
发布于 2018-05-13 08:17:07
您必须使用经典函数而不是箭头函数。this on箭头函数指的是单击的HTMLDocument和对象。这就是为什么你没有得到正确的结果。您正在从HTMLDocument获得更高的值。
$(".heroes-pic").on("click", function() {
player = $(this).attr("value");
console.log(player);
});<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
比如:
$(".heroes-pic").on("click", (event) => {
player = $(event.currentTarget).attr("value");
console.log(player);
});<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>
发布于 2018-05-13 08:15:58
这是因为您使用的是一个箭头函数,它将this参数绑定到封闭范围的下面。
请参阅this
代之以下列功能:
$(".heroes-pic").on("click", function () {
player = $(this).attr("value");
console.log(player);
}https://stackoverflow.com/questions/50314087
复制相似问题