在html中,有些图像具有相同的类名但ID不同。
<IMG STYLE="position:absolute; TOP:35px; LEFT:170px; WIDTH:25px; HEIGHT:20px; background:red;" SRC="../image_collection/xx.png" class="allBtns" id="btn1">
<IMG STYLE="position:absolute; TOP:95px; LEFT:50px; WIDTH:25px; HEIGHT:20px; background:red;" SRC="../image_collection/yy.png" class="allBtns" id="btn2">
<IMG STYLE="position:absolute; TOP:295px; LEFT:250px; WIDTH:25px; HEIGHT:20px; background:red;" SRC="../image_collection/yy.png" class="allBtns" id="btn3">
..........
如果单击图像,我想要已单击的图像的ID。
我尝试了以下操作,它返回了完整的ID列表:
$(".allBtns").on("click", function(event)
{
var ids = $('.allBtns').map(function() {
return this.id;
}).get();
alert(ids);
})
如何获取被点击的图片ID?
答案 0 :(得分:4)
this是指单击的当前元素。
$(".allBtns").on("click", function(event) {
alert(this.id); // alert the id of current element
});
答案 1 :(得分:1)
另一种方法是使用事件目标获取id
:
$(document).ready(function(){
$(".allBtns").on('click', function(e){
console.log(e.target.id);
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<IMG STYLE="position:absolute; TOP:35px; LEFT:170px; WIDTH:25px; HEIGHT:20px; background:red;" SRC="../image_collection/xx.png" class="allBtns" id="btn1">
<IMG STYLE="position:absolute; TOP:95px; LEFT:50px; WIDTH:25px; HEIGHT:20px; background:red;" SRC="../image_collection/yy.png" class="allBtns" id="btn2">
<IMG STYLE="position:absolute; TOP:295px; LEFT:250px; WIDTH:25px; HEIGHT:20px; background:red;" SRC="../image_collection/yy.png" class="allBtns" id="btn3">
答案 2 :(得分:0)
$('.hello').click(function(){
var id = $(this).attr('id');
$('.input').val(id);
});
<button class='hello'>click to get Id</button>
<button class='hello'>click to get Id</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class='hello' id='1'>click to get Id</button>
<button class='hello' id='2'>click to get Id</button>
<input class='input' type="text" />
答案 3 :(得分:-1)
$('.allBtns').on('click', function(e){
console.log(this.id);
console.log(e.target.id)
})