Cómo conseguir que los niños de la $(this) selector?
-
08-07-2019 - |
Pregunta
Tengo un diseño similar a este:
<div id="..."><img src="..."></div>
y me gustaría utilizar un selector de jQuery para seleccionar el niño img
dentro de la div
en haga clic en.
Para obtener el div
, Tengo este selector:
$(this)
¿Cómo puedo conseguir que el niño se img
el uso de un selector?
Solución
El constructor jQuery acepta un segundo parámetro llamado context
que puede ser usado para anular el contexto de la selección.
jQuery("img", this);
Que es lo mismo que usar .find()
de esta manera:
jQuery(this).find("img");
Si las imágenes que desea son solo descendientes directos del elemento seleccionado, también puede utilizar .children()
:
jQuery(this).children("img");
Otros consejos
También puedes usar
$(this).find('img');
que devolvería todos los img
s que son descendientes de div
Si necesita obtener el primer img
que está exactamente en un nivel, puede hacerlo
$(this).children("img:first")
Si su etiqueta DIV es seguida inmediatamente por la etiqueta IMG, también puede usar:
$(this).next();
Los hijos directos son
$('> .child', this)
Puede encontrar todos los elementos img del elemento principal div a continuación
$(this).find('img') or $(this).children('img')
Si quieres un elemento img específico, puedes escribir así
$(this).children('img:nth(n)')
// where n is the child place in parent list start from 0 onwards
Su div contiene solo un elemento img. Entonces para esto a continuación es correcto
$(this).find("img").attr("alt")
OR
$(this).children("img").attr("alt")
Pero si su div contiene más elementos img como a continuación
<div class="mydiv">
<img src="test.png" alt="3">
<img src="test.png" alt="4">
</div>
entonces no puede usar el código superior para encontrar el valor alternativo del segundo elemento img. Entonces puedes probar esto:
$(this).find("img:last-child").attr("alt")
OR
$(this).children("img:last-child").attr("alt")
Este ejemplo muestra una idea general de cómo puede encontrar un objeto real dentro del objeto padre. Puede usar clases para diferenciar su objeto hijo. Eso es fácil y divertido. es decir
<div class="mydiv">
<img class='first' src="test.png" alt="3">
<img class='second' src="test.png" alt="4">
</div>
Puede hacer esto de la siguiente manera:
$(this).find(".first").attr("alt")
y más específico como:
$(this).find("img.first").attr("alt")
Puede usar find o children como el código anterior. Para obtener más información, visite http://api.jquery.com/children/ y encuentre http://api.jquery.com/find/ . Ver ejemplo http://jsfiddle.net/lalitjs/Nx8a6/
Formas de referirse a un niño en jQuery. Lo resumí en el siguiente jQuery:
$(this).find("img"); // any img tag child or grandchild etc...
$(this).children("img"); //any img tag child that is direct descendant
$(this).find("img:first") //any img tag first child or first grandchild etc...
$(this).children("img:first") //the first img tag child that is direct descendant
$(this).children("img:nth-child(1)") //the img is first direct descendant child
$(this).next(); //the img is first direct descendant child
Sin conocer el ID del DIV, creo que podría seleccionar el IMG de esta manera:
$("#"+$(this).attr("id")+" img:first")
Pruebe este código:
$(this).children()[0]
Puede usar cualquiera de los siguientes métodos:
1 find ():
$(this).find('img');
2 hijos ():
$(this).children('img');
jQuery's each
es una opción:
<div id="test">
<img src="testing.png"/>
<img src="testing1.png"/>
</div>
$('#test img').each(function(){
console.log($(this).attr('src'));
});
Puede utilizar Niño Selecor para hacer referencia a que el niño los elementos disponibles en el padre.
$(' > img', this).attr("src");
Y el de abajo es que si usted no tiene referencia a $(this)
y desea para referencia img
disponible dentro de un div
de otra función.
$('#divid > img').attr("src");
También esto debería funcionar:
$("#id img")
Aquí hay un código funcional, puede ejecutarlo (es una demostración simple).
Cuando hace clic en el DIV obtiene la imagen de algunos métodos diferentes, en esta situación " this " es el DIV.
$(document).ready(function() {
// When you click the DIV, you take it with "this"
$('#my_div').click(function() {
console.info('Initializing the tests..');
console.log('Method #1: '+$(this).children('img'));
console.log('Method #2: '+$(this).find('img'));
// Here, i'm selecting the first ocorrence of <IMG>
console.log('Method #3: '+$(this).find('img:eq(0)'));
});
});
.the_div{
background-color: yellow;
width: 100%;
height: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="my_div" class="the_div">
<img src="...">
</div>
¡Espero que ayude!
Usted puede tener de 0 a muchas <img>
tags dentro de su <div>
.
Para encontrar un elemento, utilice un .find()
.
Para mantener su código de seguros, el uso de un .each()
.
El uso de .find()
y .each()
junto evita null errores de referencia en el caso de 0 <img>
los elementos, mientras que también permite el manejo de múltiples <img>
elementos.
// Set the click handler on your div
$("body").off("click", "#mydiv").on("click", "#mydiv", function() {
// Find the image using.find() and .each()
$(this).find("img").each(function() {
var img = this; // "this" is, now, scoped to the image element
// Do something with the image
$(this).animate({
width: ($(this).width() > 100 ? 100 : $(this).width() + 100) + "px"
}, 500);
});
});
#mydiv {
text-align: center;
vertical-align: middle;
background-color: #000000;
cursor: pointer;
padding: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="mydiv">
<img src="" width="100" height="100"/>
</div>
$(document).ready(function() {
// When you click the DIV, you take it with "this"
$('#my_div').click(function() {
console.info('Initializing the tests..');
console.log('Method #1: '+$(this).children('img'));
console.log('Method #2: '+$(this).find('img'));
// Here, i'm selecting the first ocorrence of <IMG>
console.log('Method #3: '+$(this).find('img:eq(0)'));
});
});
.the_div{
background-color: yellow;
width: 100%;
height: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="my_div" class="the_div">
<img src="...">
</div>