0

我的结构看起来像这样:

<div class="wanted" id="but-not-really">
    <div class="wanted">
        <div class="dad">
            <input class="reference"/>
            <input class="wanted"/>
            <input class="bro3"/>
        </div>
    </div>
</div>

我想获得我的元素(在我的 JS 循环中)的祖先 ( div.wanted) 或兄弟 ( ) 的宽度,这取决于哪个最接近。input.wanted.reference$(this)

如果我只想通过祖先寻找,我会使用$(this).closest('.wanted').width(). 如果我只想通过兄弟姐妹寻找,我会使用$(this).siblings('.wanted').width().

我尝试使用$(this).parents().find('.wanted').width(),但网页包含干扰文档的其他元素。这就是为什么我要.wanted在兄弟姐妹和祖先中寻找最接近的元素。

解决方案 N°1(感谢@undefined):

首先使用方法检查兄弟姐妹siblings,如果集合为空,则使用closest.

var width = $(this).siblings('.wanted').length === 0
             ? $(this).closest('.wanted').css('width')
             : $(this).siblings('.wanted').css('width');
4

1 回答 1

0

How about something like this?

var closestNextDistance = $(this).nextUntil('.wanted').length;
var closestPrevDistance = $(this).prevUntil('wanted').length;
var closestParentDistance = $(this).parentsUntil('.wanted').length;

Then compare the distances to check which one is the closest element, if the parent is closer, call

$(this).closest(selector).css('width')

else if one of the siblings is closer then call

$(this).prevAll('.wanted').css('width')

or

$(this).nextAll('.wanted').css('width')

See http://jsfiddle.net/3z7t5gqn/

You'll need to add few checks there to see if there's a next('.wanted') sibling when nextUntil returns 0 but if you turn it into a little function, you could re-use it.

于 2014-09-16T10:27:13.047 回答