获取每个可见图像的ID

时间:2015-08-04 02:41:56

标签: javascript jquery

我有21个图像动态加载到多个div中。以下是图像的示例。

<img src="fruits/lychee.png" class ="fruit" id="fruitl156">
<img src="fruits/cranberry.png" class ="fruit" id="fruitl141">
<img src="fruits/avocado.png" class ="fruit" id="fruitl214">

当页面加载3到6个随机图像时将会可见。我希望在单击$('#findVisible')时获取每个图像的ID。这是我的代码,但它没有提醒身份证?如何获取每个可见图像的ID?

$('#findVisible').click(function(){
     if ($('.fruit:visible').length > 0) {
        //dosomething
        $('.fruit:visible').each(function(){
             var g = $(this.id);
             alert(g) //DOES NOT WORK?
        });      
        return false;
     }
});

1 个答案:

答案 0 :(得分:1)

$

中删除$(this.id)包装

&#13;
&#13;
$('#findVisible').click(function() {
  if ($('.fruit:visible').length > 0) {
    //dosomething
    $('.fruit:visible').each(function() {
      var g = this.id;
      alert(g) //DOES NOT WORK?
    });
    return false; //to stop refreshing the page
  }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<img src="fruits/lychee.png" class="fruit" id="fruitl156">
<img src="fruits/cranberry.png" class="fruit" id="fruitl141">
<img src="fruits/avocado.png" class="fruit" id="fruitl214">
<button id="findVisible">click</button>
&#13;
&#13;
&#13;