jQuery最接近属性过滤器 [英] jQuery closest with attribute filter

查看:66
本文介绍了jQuery最接近属性过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

jQuery 1.5.1是否支持最接近的方法中的属性选择器?

Does jQuery 1.5.1 support attribute selectors in the closest method?

鉴于以下结构, el 表示值为513的复选框,我正试图通过

Given the structure below, el represents the checkbox with the value 513, and I'm trying to reach up and check the ancestor checkbox with the value of 0 with

$(el).closest("input[value='0']")[0].checked = true;

但选择器什么也没有返回。

but the selector is returning nothing.

我错过了什么傻事?

编辑

叹气,所以值为0的复选框不是 el 的祖先,只是 ul 祖先的兄弟姐妹。我得到它与

Sigh, so the checkbox with value 0 isn't an ancestor to el, just a sibling of the ul ancestor. I got it to work with

$(el).closest("ul").siblings("input[value='0']")[0].checked = true;

但我们有更清洁的方式来抓住它吗?

But us there a cleaner way to grab it?

推荐答案

.closest()方法 支持属性选择器与任何其他jQuery方法相同(虽然我不知道你提到的jQuery的特定版本),但这里的问题是 .closest()不只是看一般附近,它通过祖先上升。您正在尝试选择的输入元素是您开始使用的元素的祖先。 (鉴于输入不能包含其他元素,它们永远不会成为任何东西的祖先......)

The .closest() method does support attribute selectors the same as any other jQuery method (although I don't know about the specific version of jQuery you mentioned), but the problem here is that .closest() doesn't just look in the general vicinity, it goes up through the ancestors. You are trying to select an input element that is not an ancestor of the element you are starting with. (Given that inputs can't contain other elements they will never be the ancestors of anything...)

你应该能够做到首先选择目标复选框的父li元素:

You should be able to do it by selecting the target checkbox's parent li element first:

$(el).closest('li:has(input[value="0"])')
     .find('input[value="0"]').prop("checked",true);

演示: http: //jsfiddle.net/Vpzyj/

当然如果你能够在顶级菜单项中添加一个类,你就不需要弄乱了你可以这样说:

Of course if you were able to add a class to the top level menu items you wouldn't need to mess around with ":has", you could just say:

$(el).closest('li.topMenu').find('input[value="0"]').prop("checked",true);

这篇关于jQuery最接近属性过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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