【问题标题】:jQuery - How do you select children of children when in the context of 'this'?jQuery - 在“this”的上下文中如何选择孩子的孩子?
【发布时间】:2010-07-28 18:04:09
【问题描述】:

在滚动包装 div 时,我需要不同的嵌套子级来做不同的事情。

一个 div 需要淡化到一个不透明度级别,另一个 div 需要做另一件事。

这一切都包裹在很多我无法篡改的东西中。

我不知道如何在 children 中调用 children....我已经尝试了 jQuery 的每个 frikkin 组合,但它就是不想玩,因为它与函数的“this”部分挂钩。

但如果我去掉“this”,它会对文档中的所有实例执行操作。

<div class="vpMedia"><li><a href="http://site.com"><div class="vpArrow"><image src="http://site.com/image1"></div><div class="vpLeft">Title</div><div class="vpRight">
<div class="vpRightImg"><image src="http://site.com/image2"></div></div></a></li></div>

我到处搜索与在孩子中寻找孩子相关的问题或主题,但遗憾的是,周围真的什么都没有。我没见过这样的:

this.children(.foo).children(#bar)

或者走这条路?

this > .foo > #bar

因为它永远不会起作用,所以 'this' 需要在引号中out。那么如果我们不能使用 em 有什么解决方案呢?

编辑 - 好的,所以这是一个非常新手的问题。抱歉,希望能帮助某个地方的初学者。感谢您的耐心等待。

【问题讨论】:

  • 请向我们展示您的真实代码。
  • 你能提供一个你遇到问题的 JS 代码的小 sn-p 吗?
  • sn-p 看起来很不对劲,不值得分享!
  • 你没有指定类名,看我的回答。

标签: jquery jquery-selectors children


【解决方案1】:

试过$(".foo&gt;#bar", this)$(this).children('.foo').children('#bar')

另外,请记住,合法的 ID 在一个页面中应该是唯一的,所以这个例子可以写成 $('#bar')...

【讨论】:

    【解决方案2】:

    你需要做.children('.vpLeft'),而不是.children('vpLeft')。您正在选择一个其 nodeName === 'vpLeft' 的元素。

    $("div .vpMedia").mouseover(function() {
        $(this).children("li").children("a").children(".vpLeft").animate({opacity: .3}, { duration: 100, queue: false });
    }).mouseout(function() {
        $(this).children("li").children("a").children(".vpLeft").animate({opacity: 1}, { duration: 100, queue: false });
    })
    

    你可以缩短它..

    $("div .vpMedia").mouseover(function() {
        $('>li>a>.vpLeft', this).animate({opacity: .3}, { duration: 100, queue: false });
    }).mouseout(function() {
        $('>li>a>.vpLeft', this).animate({opacity: 1}, { duration: 100, queue: false });
    })
    

    也是&lt;img&gt; 不是&lt;image&gt;

    【讨论】:

      【解决方案3】:

      要调用孩子的孩子,你可以这样做:

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

      或者你可以使用find,它类似于children,只是它是scans the DOM recursively

      $(this).find("#bar");
      

      【讨论】:

      • 工作!谢谢 :-) 我喜欢这个查找选择器
      • 请记住,find 不是最有效的方法,因为它是递归的。如果搜索应该是唯一的 ID,我会在上面提到的@AKX 处进行。
      【解决方案4】:

      我相信 $(this).find() 会为此工作。

      查看http://api.jquery.com/find/ 了解有关查找的更多信息。

      【讨论】:

        猜你喜欢
        • 2012-12-13
        • 2010-09-23
        • 2013-04-23
        • 2011-02-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多