Risposte:
Il costruttore jQuery accetta un secondo parametro chiamato contextche può essere utilizzato per sovrascrivere il contesto della selezione.
jQuery("img", this);
Che è lo stesso che usare in .find()questo modo:
jQuery(this).find("img");
Se le img che desideri sono solo discendenti diretti dell'elemento cliccato, puoi anche usare .children():
jQuery(this).children("img");
Puoi anche usare
$(this).find('img');
che restituirebbe tutti imgi discendenti deldiv
$(this).children('img')sarebbe meglio. ad es. <div><img src="..." /><div><img src="..." /></div></div>perché presumibilmente l'utente vuole trovare imgs di 1 ° livello.
Se devi ottenere il primo imgche scende esattamente di un livello, puoi farlo
$(this).children("img:first")
:firstcorrispondere solo " verso il basso esattamente un livello ", o lo fa corrispondere la "prima" img che è stato trovato?
.children()è da dove viene il "down esattamente di un livello" ed :firstè da dove viene il "primo".
.find()invece di.children()
thisera già un riferimento al <div>contenimento del <img>, tuttavia se hai più livelli di tag da attraversare dal riferimento che avevi, allora sicuramente potresti comporre più di una children()chiamata
Se il tuo tag DIV è immediatamente seguito dal tag IMG, puoi anche usare:
$(this).next();
I bambini diretti lo sono
$('> .child-class', this)
Puoi trovare tutti gli elementi img del div parent come di seguito
$(this).find('img') or $(this).children('img')
Se vuoi un elemento img specifico, puoi scrivere così
$(this).children('img:nth(n)')
// where n is the child place in parent list start from 0 onwards
Il tuo div contiene solo un elemento img. Quindi per questo sotto è giusto
$(this).find("img").attr("alt")
OR
$(this).children("img").attr("alt")
Ma se il tuo div contiene più elementi img come di seguito
<div class="mydiv">
<img src="test.png" alt="3">
<img src="test.png" alt="4">
</div>
quindi non puoi usare il codice superiore per trovare il valore alt del secondo elemento img. Quindi puoi provare questo:
$(this).find("img:last-child").attr("alt")
OR
$(this).children("img:last-child").attr("alt")
Questo esempio mostra un'idea generale di come trovare l'oggetto reale all'interno dell'oggetto genitore. È possibile utilizzare le classi per differenziare l'oggetto figlio. È facile e divertente. vale a dire
<div class="mydiv">
<img class='first' src="test.png" alt="3">
<img class='second' src="test.png" alt="4">
</div>
Puoi farlo come di seguito:
$(this).find(".first").attr("alt")
e più specifico come:
$(this).find("img.first").attr("alt")
Puoi usare find o children come sopra. Per ulteriori informazioni, visitare Bambini http://api.jquery.com/children/ e Trova http://api.jquery.com/find/ . Vedi esempio http://jsfiddle.net/lalitjs/Nx8a6/
Modi per fare riferimento a un bambino in jQuery. L'ho riassunto nel seguente 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
Senza conoscere l'ID del DIV penso che potresti selezionare l'IMG in questo modo:
$("#"+$(this).attr("id")+" img:first")
Prova questo codice:
$(this).children()[0]
$($(this).children()[0]).
$(this:first-child)
$($(this).children()[x])usare $(this).eq(x)o se vuoi il primo, giusto $(this).first().
È possibile utilizzare uno dei seguenti metodi:
1 find ():
$(this).find('img');
2 bambini():
$(this).children('img');
jQuery eachè un'opzione:
<div id="test">
<img src="testing.png"/>
<img src="testing1.png"/>
</div>
$('#test img').each(function(){
console.log($(this).attr('src'));
});
È possibile utilizzare Child Selecor per fare riferimento agli elementi figlio disponibili all'interno del padre.
$(' > img', this).attr("src");
E il seguito è se non si ha riferimento a $(this)e si desidera fare riferimento imgdisponibile all'interno di divda un'altra funzione.
$('#divid > img').attr("src");
Ecco un codice funzionale, puoi eseguirlo (è una semplice dimostrazione).
Quando si fa clic sul DIV si ottiene l'immagine da alcuni metodi diversi, in questa situazione "questo" è il 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>
Spero che sia d'aiuto!
Potresti avere da 0 a molti <img>tag all'interno del tuo <div>.
Per trovare un elemento, utilizzare a .find().
Per proteggere il tuo codice, usa a .each().
L'uso .find()e .each()insieme impedisce errori di riferimento nulli nel caso di 0 <img>elementi consentendo al contempo la gestione di più <img>elementi.
// 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>
$("body").off("click", "#mydiv").on("click", "#mydiv", function() {
event.stopImmediatePropagation()l'elemento per evitare che ciò accadesse.
$(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>
Puoi usare
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
$(this).find('img');
</script>
Se il tuo img è esattamente il primo elemento all'interno di div, allora prova
$(this.firstChild);