Jak zdobyć dzieci $(tego) selektora?

Mam układ podobny do tego:

<div id="..."><img src="..."></div>

I chce użyć selektora jQuery, aby wybrać potomka img wewnątrz div Po kliknięciu.

Aby uzyskać div, mam taki selektor:

$(this)

Jak mogę uzyskać dziecko img za pomocą selektora?

Author: Kamil Kiełczewski, 2008-11-20

18 answers

Konstruktor jQuery przyjmuje drugi parametr o nazwie context które mogą być użyte do nadpisania kontekstu zaznaczenia.

jQuery("img", this);

Który jest taki sam jak przy użyciu .find() Tak:

jQuery(this).find("img");

Jeśli pożądane imgs są tylko bezpośrednimi potomkami klikniętego elementu, Możesz również użyć .children():

jQuery(this).children("img");
 2887
Author: Simon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-06-25 20:45:42

Możesz również użyć

$(this).find('img');

Który zwróci wszystkie imgs, które są potomkami div

 475
Author: philnash,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-11-20 21:23:15

Jeśli chcesz uzyskać pierwszy img, który jest dokładnie o jeden poziom niżej, możesz to zrobić

$(this).children("img:first")
 138
Author: rakslice,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-07-21 18:47:31

Jeśli twój znacznik DIV jest natychmiast po znaczniku IMG, możesz również użyć:

$(this).next();
 76
Author: Roccivic,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-11-27 00:03:20

The direct children is

$('> .child-class', this)
 70
Author: Rayron Victor,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-12-19 18:29:13

Możesz znaleźć wszystkie elementy img rodzica div jak poniżej

$(this).find('img') or $(this).children('img')

Jeśli chcesz mieć określony element img możesz napisać tak:

$(this).children('img:nth(n)')  
// where n is the child place in parent list start from 0 onwards

Twój div zawiera tylko jeden element img. Tak więc poniżej jest prawo

 $(this).find("img").attr("alt")
                  OR
  $(this).children("img").attr("alt")

Ale jeśli twój div zawiera więcej elementów img jak poniżej

<div class="mydiv">
    <img src="test.png" alt="3">
    <img src="test.png" alt="4">
</div>

Wtedy nie można użyć górnego kodu, aby znaleźć wartość alt drugiego elementu img. Więc możesz spróbować tego:

 $(this).find("img:last-child").attr("alt")
                   OR
 $(this).children("img:last-child").attr("alt")

Ten przykład pokazuje ogólną ideę, że jak można znaleźć rzeczywisty obiekt w obiekt nadrzędny. Możesz używać klas do rozróżniania obiektów potomnych. To jest łatwe i przyjemne. tj.

<div class="mydiv">
    <img class='first' src="test.png" alt="3">
    <img class='second' src="test.png" alt="4">
</div>

Możesz to zrobić jak poniżej:

 $(this).find(".first").attr("alt")

I bardziej szczegółowe jako:

 $(this).find("img.first").attr("alt")

Możesz użyć find lub children jak powyższy kod. Więcej odwiedzin Dla Dzieci http://api.jquery.com/children / i znaleźć http://api.jquery.com/find/. Zobacz przykład http://jsfiddle.net/lalitjs/Nx8a6/

 41
Author: Lalit Kumar Maurya,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-12-04 04:59:04

Sposoby odwoływania się do dziecka w jQuery. Podsumowałem to w następującym 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
 35
Author: Oskar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-01-25 13:25:03

Nie znając ID DIV myślę, że można wybrać IMG tak:

$("#"+$(this).attr("id")+" img:first")
 31
Author: Adam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-11-20 19:56:20

Wypróbuj ten kod:

$(this).children()[0]
 31
Author: Maxam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-06-17 18:40:39

Możesz użyć jednej z następujących metod:

1 Znajdź():

$(this).find('img');

2 dzieci():

$(this).children('img');
 23
Author: Mike Clark,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-21 06:36:05

JQuery ' s each jest jedną z opcji:

<div id="test">
    <img src="testing.png"/>
    <img src="testing1.png"/>
</div>

$('#test img').each(function(){
    console.log($(this).attr('src'));
});
 21
Author: Thirumalai murugan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-06-23 07:11:48

Możesz użyć Selecoru potomnego do odwoływania się do elementów potomnych dostępnych w rodzicu.

$(' > img', this).attr("src");

I poniżej jest, jeśli nie masz odniesienia do $(this) i chcesz odwołać się do img dostępne w div z innej funkcji.

 $('#divid > img').attr("src");
 15
Author: Dennis R,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-07-25 21:56:40

Również to powinno działać:

$("#id img")
 12
Author: tetutato,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-21 06:22:13

Oto kod funkcjonalny, możesz go uruchomić (to prosta demonstracja).

Po kliknięciu DIV otrzymujesz obraz z różnych metod, w tej sytuacji" to " jest 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>
Mam nadzieję, że to pomoże!
 8
Author: RPichioli,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-09 13:12:55

Możesz mieć od 0 do wielu <img> tagów wewnątrz <div>.

Aby znaleźć element, użyj .find().

Aby Twój kod był bezpieczny, użyj .each().

Użycie .find() i .each() razem zapobiega błędom odniesienia null W przypadku 0 <img> elementów, jednocześnie pozwalając na obsługę wielu <img> elementów.

// 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>
 5
Author: Jason Williams,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-11 20:01:14

$(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>
 4
Author: Sumit Lahiri,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-05 13:27:33

Jeśli twój img jest dokładnie pierwszym elementem w div to spróbuj

$(this.firstChild);

$( "#box" ).click( function() {
  let img = $(this.firstChild);
  console.log({img});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="box"><img src="https://picsum.photos/seed/picsum/300/150"></div>
 0
Author: Kamil Kiełczewski,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-05-07 08:44:55

You could use

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
 $(this).find('img');
</script>
 -1
Author: Hassan Fayyaz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-09-19 07:18:23