jQuery 通过属性值获取元素的子元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16117883/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:28:46  来源:igfitidea点击:

Get child of element by attribute value

jquerydomselector

提问by Raphael Jeger

I have a jQuery object representing a DIV:

我有一个代表 DIV 的 jQuery 对象:

$rel = $('#rel_'+rel.id);

In that DIV, there is a BUTTON with my custom attribute "rid" set to rel.id

在那个 DIV 中,有一个 BUTTON,我的自定义属性“rid”设置为 rel.id

I need to select that button, it works like this:

我需要选择那个按钮,它的工作原理是这样的:

$("[rid='"+rel.id+"']").html();

But I think that's not the fastest possible solution as it needs to parse the whole DOM for that and because I know the button is always inside the DIV, I could avoid that.

但我认为这不是最快的解决方案,因为它需要为此解析整个 DOM,而且因为我知道按钮总是在 DIV 内,所以我可以避免这种情况。

I tried it with the following code:

我用下面的代码试了一下:

$rel.children("[rid='"+rel.id+"']").html();

but that didn't work.

但这没有用。

Thanks for any help.

谢谢你的帮助。

回答by T.J. Crowder

If it may not be an immediate child, you'll want findrather than children(which only looks at immediate children):

如果它可能不是直接的孩子,你会想要find而不是children(它只看直接的孩子):

$rel.find("[rid='"+rel.id+"']").html();