【问题标题】:How can I do sub selects on already selected element?如何对已选择的元素进行子选择?
【发布时间】:2011-03-28 09:23:01
【问题描述】:

标记:

<div class="foo">
    <img src="loading.gif" class="loading" style="display: none;" />
</div>

Js:

$("div[class='foo']").click(function(e) {
    e.preventDefault();
    $(this).hide();
    $(/* somehow select the loading img of exactly this div with class foo (not others) */).show();
});

【问题讨论】:

    标签: jquery jquery-selectors


    【解决方案1】:

    如果你想要给定元素的任何后代,你可以使用find():

    $(this).find(".foo");
    

    如果你知道你只想搜索一级子元素,你可以使用children()

    $(this).children(".foo");
    

    【讨论】:

    • 我喜欢给孩子们的提示(".foo")
    • 确实正确——但根据您对问题标题中sub selects的理解方式,初始集合的元素可能是可供选择的候选对象。但据我所知,find 不会考虑后代。我不知道是否有办法在“自我或后代”中找到...
    【解决方案2】:
    $("div[class='foo']").click(function(e) {
        e.preventDefault();
        $(this).hide();
        $('img.loading', this).show();
    });
    

    【讨论】:

    • 哇!您可以将上下文传递给 $-selector!不错。
    • @randomguy:选择器上下文映射到 find() 方法,因此$('img.loading', this)$(this).find('img.loading') 相同。我认为选择器上下文要“更好”。
    【解决方案3】:

    你可以使用

    $(this).find("img").show();
    

    $(this).find("img.loading").show();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-14
      • 2018-02-09
      • 2019-05-21
      相关资源
      最近更新 更多