2009-09-24 16 views
50

Usando jQuery, ¿cómo selecciono un solo elemento secundario? He mirado en la API de desplazamiento y sé que puedo seleccionar todos los elementos secundarios inmediatos img elementos como este:¿Cómo seleccionar un elemento hijo único usando jQuery?

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

Y para seleccionar el primer elemento secundario img que podría utilizar un subíndice como esto:

$(this).children('img')[0]; 

Pero supongo que estoy un poco sorprendido de que yo no puedo hacer esto:

$(this).child('img'); // no subscript, returns single element 

O he perdido algo?

Respuesta

32

No. Cada función de jQuery devuelve un objeto jQuery, y así es como funciona. Esta es una parte crucial de la magia de jQuery.

Si desea acceder al elemento subyacente, usted tiene tres opciones ...

  1. no utilice jQuery
  2. Uso [0] hacer referencia a ella
  3. Extender jQuery para hacer lo que quiera. ..

    $.fn.child = function(s) { 
        return $(this).children(s)[0]; 
    } 
    
+0

¡Ah, ja! Eso fue todo. Esperaba el elemento img (tratando de hacer referencia a su propiedad 'src') en lugar del objeto jQuery. Ahora solo usaré 'attr()' para obtener la propiedad 'src'. –

+0

Gracias por 3) también. Podría considerar hacer eso. :) –

+6

No. Si uso por ejemplo 'find (" div ") [0]' No obtendré 'div' como un objeto jQuery. Obtendré 'div' como HTMLElement. Para obtener 'div' como objeto jQuery uno tiene que usar' .eq (0) ', como dice Greg a continuación. – Green

80

Creo que lo que quiere hacer es la siguiente:

$(this).children('img').eq(0); 

esto le dará un objeto jQuery que contiene el primer elemento img, mientras que

$(this).children('img')[0]; 

le dará el elemento img sí.

+1

Tenga en cuenta que el uso de buscar como en la primera respuesta le dará todos los elementos descendientes, mientras que el niño solo le dará hijos directos. – Greg

3

¿Quizás de esta manera?

$('img', this)[0] 
+0

Esto no necesariamente seleccionará el elemento secundario directo y, al igual que la respuesta aceptada, devolverá el elemento, no el objeto jQuery. – Septagram

0
<html> 
<title> 

    </title> 
    <meta name="viewport" content="width=device-width, initial-scale=1"> 
    <link rel="stylesheet" type="text/css" href="assets/css/bootstrap.css"> 
<body> 




<!-- <asp:LinkButton ID="MoreInfoButton" runat="server" Text="<%#MoreInfo%>" > --> 
<!-- </asp:LinkButton> --> 
<!-- </asp:LinkButton> --> 

<br /> 
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource1"> 
<div> 
<a><span id="imgDownArrow_0" class="glyphicon glyphicon-chevron-right " runat="server"> MoreInformation</span></a> 
<div id="parent" class="dataContentSectionMessages" style="display:none"> 
    <!-- repeater1 starts --> 
     <!-- <sc:text field="Event Description" runat="server" item="<%#Container.DataItem %>" /> --> 
      <ul > 
       <li ><h6><strong>lorem</strong></h6></li> 
       <li ><h6><strong>An assigned contact who knows you and your lorem analysis system</strong></h6></li> 
       <li ><h6><strong>Internet accessible on-demand information and an easy to use internet shop</strong></h6></li> 
       <li ><h6><strong>Extensive and flexible repair capabilities at any location</strong></h6></li> 
       <li ><h6><strong>Full Service Contracts</strong></h6></li> 
       <li ><h6><strong>Maintenance Contracts</strong></h6></li> 
      </ul> 
    <!-- repeater1 ends --> 
</div> 
</div> 
<div> 
<a><span id="imgDownArrow_0" class="glyphicon glyphicon-chevron-right " runat="server"> MoreInformation</span></a> 
<div id="parent" class="dataContentSectionMessages" style="display:none"> 
    <!-- repeater1 starts --> 
     <!-- <sc:text field="Event Description" runat="server" item="<%#Container.DataItem %>" /> --> 
      <ul > 
       <li ><h6><strong>lorem</strong></h6></li> 
       <li ><h6><strong>An assigned contact who knows you and your lorem analysis system</strong></h6></li> 
       <li ><h6><strong>Internet accessible on-demand information and an easy to use internet shop</strong></h6></li> 
       <li ><h6><strong>Extensive and flexible repair capabilities at any location</strong></h6></li> 
       <li ><h6><strong>Full Service Contracts</strong></h6></li> 
       <li ><h6><strong>Maintenance Contracts</strong></h6></li> 
      </ul> 
    <!-- repeater1 ends --> 
</div> 
</div> 
<div> 
<a><span id="imgDownArrow_0" class="glyphicon glyphicon-chevron-right " runat="server"> MoreInformation</span></a> 
<div id="parent" class="dataContentSectionMessages" style="display:none"> 
    <!-- repeater1 starts --> 
     <!-- <sc:text field="Event Description" runat="server" item="<%#Container.DataItem %>" /> --> 
      <ul > 
       <li ><h6><strong>lorem</strong></h6></li> 
       <li ><h6><strong>An assigned contact who knows you and your lorem analysis system</strong></h6></li> 
       <li ><h6><strong>Internet accessible on-demand information and an easy to use internet shop</strong></h6></li> 
       <li ><h6><strong>Extensive and flexible repair capabilities at any location</strong></h6></li> 
       <li ><h6><strong>Full Service Contracts</strong></h6></li> 
       <li ><h6><strong>Maintenance Contracts</strong></h6></li> 
      </ul> 
    <!-- repeater1 ends --> 
</div> 
</div> 
<div> 
<a><span id="imgDownArrow_0" class="glyphicon glyphicon-chevron-right " runat="server"> MoreInformation</span></a> 
<div id="parent" class="dataContentSectionMessages" style="display:none"> 
    <!-- repeater1 starts --> 
     <!-- <sc:text field="Event Description" runat="server" item="<%#Container.DataItem %>" /> --> 
      <ul > 
       <li ><h6><strong>lorem</strong></h6></li> 
       <li ><h6><strong>An assigned contact who knows you and your lorem analysis system</strong></h6></li> 
       <li ><h6><strong>Internet accessible on-demand information and an easy to use internet shop</strong></h6></li> 
       <li ><h6><strong>Extensive and flexible repair capabilities at any location</strong></h6></li> 
       <li ><h6><strong>Full Service Contracts</strong></h6></li> 
       <li ><h6><strong>Maintenance Contracts</strong></h6></li> 
      </ul> 
    <!-- repeater1 ends --> 
</div> 
</div> 




</asp:Repeater> 


</body> 
<!-- Predefined JavaScript --> 
<script src="jquery.js"></script> 
<script src="bootstrap.js"></script> 

<script> 

$(function() { 
     $('a').click(function() { 
      $(this).parent().children('.dataContentSectionMessages').slideToggle(); 
     }); 
    }); 

    </script> 


</html> 
+0

$ (function() {$ ('a') haga clic en (function() {$ (este) .parent() niños() slideToggle()..' DataContentSectionMessages.;. });} ) ; esta consulta ayudará a obtener el elemento hijo de un padre –

Cuestiones relacionadas