2016-05-16 63 views
2

这是我的代码从HTML得到ID:我需要使用jQuery

$('.image1').click(function(){ 
    $('.loader').show(); 
    function preloadImages(images, callback) { 
     var count = images.length; 
     var loaded = 0; 
     $(images).each(function() { 
      $('<img>').attr('src', this).load(function() { 
       loaded++; 
       if (loaded === count) { 
        callback(); 
       } 
      }); 
     }); 
    }; 

    preloadImages(["../images/Wedding_p/large/1.jpg",          
      "../images/Wedding_p/large/2.jpg", 
      "../images/Wedding_p/large/3.jpg", 
      "../images/Wedding_p/large/4.jpg", 
      "../images/Wedding_p/large/5.jpg"], function() { 
       alert("DONE"); 
       // In here I need to get id of '.image1' image. 
      } 

这是HTML:

<div> 
    <img src = '1.jpg' data-id='1' class = 'image1'> 
    <img src = '2.jpg' data-id='2' class = 'image1'> 
    <img src = '3.jpg' data-id='3' class = 'image1'> 
</div> 

当我点击图片,我需要点击图像的数据ID ;我怎样才能使用我的jQuery代码。

+1

使用$(这).attr ( '数据-ID'); –

+0

我尝试,但警报说undefined .. PLZ给我另一种选择。 –

+1

商店$(这)给一个变量 $(”图像1' )点击(函数(){ VAR _this = $(本); 然后 警报( “DONE”); 警报(_this .attr('data-id')); –

回答

1

试试这个:

$(document).on('click', '.image1', function() { 
    alert($(this).data("id")); 
}); 
+0

是的,我尝试了但它不工作... –

+0

尝试alert($(this).attr(“数据ID“)); –

+0

谢谢你回答我的问题.. PLZ给我另一种选择。 –

4

$(document).ready(function() { 
 
    
 
    $("img").click(function() { 
 
     alert($(this).attr('data-id')); 
 
}); 
 
    
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> 
 
<div> 
 
    <img src = '1.jpg' data-id='1' class = 'image1'> 
 
     <img src = '2.jpg' data-id='2' class = 'image1'> 
 
     <img src = '3.jpg' data-id='3' class = 'image1'> 
 

 
</div>

0

您可以使用下面的代码来获取数据-id属性的值

$(this).attr('data-id'); 
+0

没有兄弟在我的代码它不工作...是我的代码正确吗? thx为回答它.. –

+0

jQuery已经有一个函数来访问数据属性https://api.jquery.com/data/ –