use - w3schools javascript jquery
Como obter os filhos do seletor $(this)? (11)
Eu tenho um layout semelhante a este:
<div id="..."><img src="..."></div>
e gostaria de usar um seletor jQuery para selecionar o filho img
dentro do div
no clique.
Para obter o div
, eu tenho este seletor:
$(this)
Como posso obter o filho img
usando um seletor?
Aqui está um código funcional, você pode executá-lo (é uma demonstração simples).
Quando você clica no DIV você obtém a imagem de alguns métodos diferentes, nessa situação "this" é o 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 ajude!
As crianças diretas são
$('> .child', this)
Formas de se referir a uma criança no jQuery. Eu resumi isso no seguinte 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
O construtor jQuery aceita um segundo parâmetro chamado context
que pode ser usado para substituir o contexto da seleção.
jQuery("img", this);
Qual é o mesmo que usar o .find()
assim:
jQuery(this).find("img");
Se as imgs desejadas forem apenas descendentes diretos do elemento clicado, você também pode usar .children()
:
jQuery(this).children("img");
Se você precisa obter o primeiro img
que está exatamente abaixo de um nível, você pode fazer
$(this).children("img:first")
Sem saber o ID do DIV eu acho que você poderia selecionar o IMG assim:
$("#"+$(this).attr("id")+" img:first")
Você pode encontrar todos os img elemento do pai div como abaixo
$(this).find('img') or $(this).children('img')
Se você quiser um elemento img específico, você pode escrever assim
$(this).children('img:nth(n)')
// where n is the child place in parent list start from 0 onwards
Seu div contém apenas um elemento img. Então, para isso abaixo está certo
$(this).find("img").attr("alt")
OR
$(this).children("img").attr("alt")
Mas se o seu div contiver mais img elemento como abaixo
<div class="mydiv">
<img src="test.png" alt="3">
<img src="test.png" alt="4">
</div>
então você não pode usar o código superior para encontrar o valor alt do segundo elemento img. Então você pode tentar isso:
$(this).find("img:last-child").attr("alt")
OR
$(this).children("img:last-child").attr("alt")
Este exemplo mostra uma ideia geral de como você pode encontrar o objeto real no objeto pai. Você pode usar classes para diferenciar seu objeto filho. Isso é fácil e divertido. ou seja
<div class="mydiv">
<img class='first' src="test.png" alt="3">
<img class='second' src="test.png" alt="4">
</div>
Você pode fazer isso abaixo:
$(this).find(".first").attr("alt")
e mais específico como:
$(this).find("img.first").attr("alt")
Você pode usar localizar ou filhos como o código acima. Para mais informações visite http://api.jquery.com/children/ e http://api.jquery.com/find/ . Veja o exemplo http://jsfiddle.net/lalitjs/Nx8a6/
Você pode ter de 0 a muitas tags <img>
dentro do seu <div>
.
Para encontrar um elemento, use um .find()
.
Para manter seu código seguro, use um .each()
.
O uso de .find()
e .each()
juntos evitam erros de referência nula no caso de elementos 0 <img>
ao mesmo tempo em que permitem o tratamento de vários elementos <img>
.
// 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>
Você pode usar um dos seguintes métodos:
1 encontrar ():
$(this).find('img');
2 crianças():
$(this).children('img');
Você também pode usar
$(this).find('img');
que retornaria todos os img
s que são descendentes do 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>