Jquery根据条件获取子元素

3

我有一个带有id='tips'的div。它有多个子元素。我需要做的是,我想获取一个div的子元素,其样式为top < 10px,并且该子元素是id='tips'的子元素。以下是代码片段。

<div id="tips">
   <div style="top: 5px; left: 150px;">
      Required Div
      <span class="arrow"></span>          
    </div>
   <div style="top: 15px; left: 150px;">
      Not-Required Div
      <span class="arrow"></span>          
    </div>
   <div style="top: 45px; left: 150px;">
      Child3
      <span class="arrow"></span>          
    </div>
</div>

只存在一个top<10px的div子元素。
1个回答

6
使用filter()函数:
var $child = $("#tips div").filter(function() {
    return parseInt($(this).css("top"), 10) < 10;
});

// you can do as needed with the element(s) here, this is just an example
$child.css("color", "#C00"); 

Example fiddle


2
哇,你比我快了10秒 :). 此外,将基数添加到 parseInt 中始终是一个好习惯。 - Marko Dumic
@MarkoDumic 谢谢 - 如果我每次忘记基数都有一便士,我就会成为一个富翁 :) - Rory McCrossan
@Rohan 这将返回所有顶部小于10的子元素,可能没有、一个或多个。 - Rory McCrossan
@RoryMcCrossan,可以帮我一下吗?我复制了同样的代码,但是无法运行。当我尝试在.filter(function() { console.log('here'); }中记录日志时,它没有被执行。可能的原因是什么? - ro ko
你把 console.log() 放在 return 前面了吗?我已经更新了我的答案,并提供了一个 fiddle,这样你就可以看到它的工作原理。 - Rory McCrossan
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接