哪个更有效:.parent().parent().parent()〜或〜parents(“.foo")〜或〜最接近(".foo") [英] Which is more efficient: .parent().parent().parent() ~or~ parents(".foo") ~or~ closest(".foo")

查看:88
本文介绍了哪个更有效:.parent().parent().parent()〜或〜parents(“.foo")〜或〜最接近(".foo")的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个A标签,该标签触发了它的曾祖父母的动画.以下所有方法都可以使用,但是哪种方法最有效,为什么?

I have an A tag which triggers the animation of it's great-great-great-grandparent. All of the following will work, but which is most efficient, and why?

$(this).parent().parent().parent().parent().parent().animate(...);

$(this).parents(".foo").animate(...);

$(this).closest(".foo").animate(...);

我怀疑第一个可能是,因为它是最明确的,但是出于维护原因(嵌套可能会更改),我更喜欢第二个.它们都出现以在实践中平稳运行.

I suspect that the first might be, as it's the most explicit, but for maintenance reasons (the nesting may change) I prefer the second. They all appear to run smoothly in practice.

推荐答案

最接近"仅在您向上移动或与"clicked"元素处于同一级别时才有用.

Well closest is only useful if you are going up or at the same level on the 'clicked' element.

例如,如果您必须遵循以下方案:

If for example you have to folowing scenario:

<div class="controls radio-other">
    <label class="radio"><input type="radio" name="item">Option one</label>
    <label class="radio"><input type="radio" name="item">Option two</label>
    <label class="radio"><input type="radio" name="item" class="other-option" data-othertarget="#otherone"> Other... </label>
    <input type="text" placeholder="Alternative answer" id="otherone" class="hidden">
</div>

然后closest('#otherone')将在$('.other-option').click()上找不到隐藏的文本字段 更好的解决方案是在这种情况下使用$(this).parentsUntil('.radio-other').find('#otherone')

Then closest('#otherone') will not find the hidden text field on $('.other-option').click() The better solution is in this scenario is to use $(this).parentsUntil('.radio-other').find('#otherone')

看着我的回答,我做了一个 jsperf ,它反映了上述情况不同的解决方案.只需使用最适合您的html方案的内容即可. 结果是parent().parent()是最快的方法,但是,如果您的html使用起来更加灵活,那么这并不总是一个好的选择.添加一个div父级,parent().parent()会中断.

Looking at my answer I made a jsperf here that reflects above scenario with different solutions. Just use what is the most usefull for your html scenario. the outcome is that parent().parent() is the fastest methode however this is not always a good option if your html is more flexible in use. Add a div parent and the parent().parent() breaks.

这篇关于哪个更有效:.parent().parent().parent()〜或〜parents(“.foo")〜或〜最接近(".foo")的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆