2011-12-27 10 views
5

Dire che ho questo:Ottieni l'attrib dell'immagine all'interno di un div?

<div class='container'> 
     <img src='image1' id='1' /> 
     <img src='image2' id='2' /> 
     ... 
</div> 
<div class='container'> 
</div> 

Ora, quando si fa clic sul contenitore, voglio ottenere l'id dell'immagine al suo interno. Se il contenitore non contiene immagini, dovrebbe apparire un errore che dice di non avere immagini nel contenitore. Altrimenti, mi piacerebbe avere una lista di tutti gli id ​​delle immagini all'interno.

utilizzando jQuery, ho questo:

$('.container').click(function() 
{ 
     var images = $(this).find('img'); 
     if(images[0] == null) { //no image found } 
     else 
     { 
      // No idea what to do here :P 
     } 
} 

Qualcuno potrebbe darmi una mano qui (mi riferisco all'interno del else {} economico)? Grazie :)

risposta

8
$(document).on("click", ".container", function(){ 
    var img = $(this).find("img"), // select images inside .container 
     len = img.length; // check if they exist 
    if(len > 0){ 
     // images found, get id 
     var attrID = img.first().attr("id"); // get id of first image 
    } else { 
     // images not found 
    } 
}); 

Example.

per ottenere un array dei id s di tutte le immagini nel contenitore:

var arr = []; // create array 
if(len > 0){ 
    // images found, get id 
    img.each(function(){ // run this for each image 
     arr.push($(this).attr("id")); // push each image's id to the array 
    }); 
} else { 
    // images not found 
} 

Example.

E, naturalmente, che tipo di persona sarei se io non vi ho dato un esempio con JS puri:

var elems = [].slice.call(document.getElementsByClassName("container")); 
elems.forEach(function(elem){ 
    elem.onclick = function(){ 
     var arr = [], 
      imgs = [].slice.call(elem.getElementsByTagName("img")); 
     if(imgs.length){ 
      imgs.forEach(function(img){ 
       var attrID = img.id; 
       arr.push(attrID); 
      }); 
      alert(arr); 
     } else { 
      alert("No images found."); 
     } 
    }; 
}); 

Example. Un po 'più complesso, e consiglio comunque di usare jQuery poiché chiarisce tutta la follia degli eventi del mouse cross browser.

0
var images = $(this).find('img'); 
    if(images.length === 0) { 
     alert('no images found'); 
    } 
    else { 
     var ids = new Array; 
     images.each(function(){ 
      ids.push($(this).attr('id')); 
     }); 
     //ids now contains all the ids of img elements 
     console.log(ids); 
    } 
+0

Ho ottenuto quella parte! Intendo cosa faccio per il resto? All'interno della dichiarazione else {}! – user1083320

+0

Ho aggiornato il codice provalo ora. – Ehtesham

0
$('.container').click(function() 
{ 
var images = $('img',this); 
if($(images).length == 0) { 
     // No Image 
    } 
    else  { 
     var ids = ''; 
     $(images).each(function(){ 
      ids = $(this).attr('id) + ","; 
     }); 
     alert(ids); 
    } 
} 
Problemi correlati