2011-12-27 24 views
5

Decir que tengo esto:Obtener imagen attrib dentro de un div?

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

Ahora, cuando hago clic en el contenedor, quiero obtener el ID de la imagen en su interior. Si el contenedor no contiene ninguna imagen, debería aparecer un error que indica que no hay imágenes en el contenedor. De lo contrario, me gustaría obtener una lista de todos los identificadores de las imágenes.

Usando jQuery, tengo esto:

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

Podría alguien por favor me ayude a cabo aquí (me refiero dentro de la declaración else {})? Gracias :)

Respuesta

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.

Para obtener una matriz de los id s de todas las imágenes en el contenedor:

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.

Y, por supuesto, ¿qué clase de persona sería si yo no te di un ejemplo con JS puros:

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 poco más complejo, y todavía recomiendo usar jQuery ya que borra toda la locura del evento del mouse de 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

¡Tengo esa parte! Quiero decir, ¿qué hago para el resto? ¡Dentro de la declaración else {}! – user1083320

+0

He actualizado el código pruébelo ahora. – 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); 
    } 
} 
Cuestiones relacionadas