jQuery pierwsze dziecko "tego"

Próbuję przekazać "to" z klikniętego zakresu do funkcji jQuery, która może następnie wykonać jQuery na pierwszym potomku tego klikniętego elementu. Nie wydaje mi się, żeby było dobrze...

<p onclick="toggleSection($(this));"><span class="redClass"></span></p>

Javascript:

function toggleSection(element) {
  element.toggleClass("redClass");
}

Jak odwołać się do :first-child elementu?

Author: BoltClock, 2010-02-16

10 answers

Jeśli chcesz zastosować selektor do kontekstu dostarczonego przez istniejący zestaw jQuery, spróbuj użyć funkcji find () :

element.find(">:first-child").toggleClass("redClass");

Jørn Schou-Rode zauważył, że prawdopodobnie chcesz znaleźć tylko pierwszy bezpośredni potomek elementu context, stąd selektor potomka (>). zwraca również uwagę , że równie dobrze można użyć funkcji children () , która jest bardzo podobna do find (), ale przeszukuje tylko jeden poziom głęboko w hierarchii (co jest potrzebujesz...):

element.children(":first").toggleClass("redClass");
 429
Author: Shog9,
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-05-23 12:02:16

Użyj children function with the :first selektor {[6] } aby uzyskać pojedynczy pierwsze dziecko element:

element.children(":first").toggleClass("redClass");
 67
Author: Jørn Schou-Rode,
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
2010-02-16 19:36:04

Dodałem jsperf test, aby zobaczyć różnicę prędkości dla różnych podejść, aby uzyskać pierwsze dziecko (łącznie 1000+ dzieci)

notif = $('#foo')

sposoby jQuery:

  1. $(":first-child", notif) - 4304 ops/sek-najszybszy
  2. notif.children(":first") - 653 ops/sek - 85% wolniej
  3. notif.children()[0] - 1416 ops/sek - 67% wolniej

natywne sposoby:

  1. JavaScript native' ele.firstChild - 4,934,323 ops / sec (wszystkie powyższe podejście jest o 100% wolniejsze w porównaniu do firstChild)
  2. rodzimy DOM ele z jQery: notif[0].firstChild - 4,913,658 ops / sec

Tak więc, pierwsze 3 podejścia jQuery nie są zalecane, przynajmniej dla first-child(wątpię, że byłoby tak w przypadku wielu innych). Jeśli masz obiekt jQuery i chcesz uzyskać first-child, to uzyskaj natywny element DOM z obiektu jQuery, używając odniesienia do tablicy[0] (zalecane) lub .get(0) i użyj ele.firstChild. To daje takie same wyniki jak zwykłe użycie JavaScript.

wszystkie testy są wykonywane w Chrome Canary build v15.0.854.0

 49
Author: manikanta,
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-08-16 22:10:29
element.children().first();
Znajdź wszystkie dzieci i zdobądź pierwsze z nich.
 11
Author: Bishal Paudel,
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-12-20 16:21:13

Czy próbowałeś

$(":first-child", element).toggleClass("redClass");

Myślę, że chcesz ustawić swój element jako kontekst dla wyszukiwania. Może być lepszy sposób, aby to zrobić, który jakiś inny guru jQuery wskoczy tutaj i wyrzuci na ciebie:)

 9
Author: theIV,
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
2010-02-16 19:34:59

Właśnie napisałem wtyczkę, która używa .firstElementChild jeśli to możliwe, i wraca do iteracji nad każdym pojedynczym węzłem, jeśli to konieczne:

(function ($) {
    var useElementChild = ('firstElementChild' in document.createElement('div'));

    $.fn.firstChild = function () {
        return this.map(function() {
            if (useElementChild) {
                return this.firstElementChild;
            } else {
                var node = this.firstChild;
                while (node) {
                    if (node.type === 1) {
                        break;
                    }
                    node = node.nextSibling;
                }
                return node;
            }
        });
    };
})(jQuery);

Nie jest tak szybki jak czyste rozwiązanie DOM, ale w testach jsperf pod Chrome 24 było kilka rzędów wielkości szybciej niż jakakolwiek inna metoda oparta na selektorze jQuery.

 4
Author: Alnitak,
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-11-15 09:08:36

Możesz użyć DOM

$(this).children().first()
// is equivalent to
$(this.firstChild)
 2
Author: Yukulélé,
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
2018-02-14 08:25:05

Proszę używać go w ten sposób po pierwsze, podaj nazwę klasy do tagu p jak " myp "

Następnie użyj następującego kodu

$(document).ready(function() {
    $(".myp").click(function() {
        $(this).children(":first").toggleClass("classname"); // this will access the span.
    })
})
 1
Author: vishal gupta,
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-09-25 13:32:40

Można to zrobić za pomocą prostej magii takiej jak Ta:

$(":first-child", element).toggleClass("redClass");

Odniesienie: http://www.snoopcode.com/jquery/jquery-first-child-selector

 1
Author: Prabhakar,
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-11-10 06:51:06

Jeśli chcesz mieć natychmiastowe pierwsze dziecko, potrzebujesz

    $(element).first();

Jeśli chcesz mieć określony pierwszy element w dom z twojego elementu, użyj poniżej

    var spanElement = $(elementId).find(".redClass :first");
    $(spanElement).addClass("yourClassHere");

Wypróbuj: http://jsfiddle.net/vgGbc/2/

 -3
Author: Amit Rathod,
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
2012-10-30 12:07:34