在 jQuery 中选择兄弟姐妹的兄弟姐妹
在下面的代码中,当用户单击 '.more'
span 元素时,我想从 img
中检索信息(例如 ID)使用 jQuery 的 >article 标签。
这是 HTML:
<article>
<img src="..." id="TR"/>
<div>some text <a>link</a> <span class="more">read more</span></div>
</article>
我已经尝试过这段代码:
$('.more').click(function () {
var id = $(this).siblings().siblings('img').attr('id');
});
但它似乎不起作用。有什么想法吗?
非常感谢!
In the following code, when the user clicks on the '.more'
span element, I want to retrieve information (eg, the ID) from the img
within the article
tag using jQuery.
Here's the HTML:
<article>
<img src="..." id="TR"/>
<div>some text <a>link</a> <span class="more">read more</span></div>
</article>
I've tried this code:
$('.more').click(function () {
var id = $(this).siblings().siblings('img').attr('id');
});
but it doesn't seem to work. Any thoughts?
Many thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以这样做:
这将查找包含
标记的父树。然后,它找到其中的第一个
![]()
标记并获取其 id 值。您不能在
$(this)
上使用.siblings()
,因为该图像不是$(this)
的直接同级图像。如果您获得了该 img 的兄弟姐妹的正确父级,则可以使用 .siblings() ,但这比我建议的要脆弱一些。例如,这也可以,但它依赖于 HTML 对象的更精确定位,任何轻微的编辑都可能会破坏此代码:或者
You can't use
.closest()
on the直接使用![]()
标记,因为 img 不是.more
对象的父对象。如果这是我的代码,我会这样做,因为它是最灵活的,并且如果稍微编辑 HTML,最不可能中断,并且即使附近有更多图像,您也一定会获得正确的 img 对象:
You can do that like this:
This looks up the parent tree for the containing
<article>
tag. Then, it finds the first<img>
tag in that and gets its id value.You can't use
.siblings()
on$(this)
because the image isn't a direct sibling of$(this)
. You could use.siblings()
if you got the right parent that the img was a sibling of, but that's a little more fragile than what I've proposed. For example, this would also work, but it relies on more precise positioning of the HTML objects and any slight edits could break this code:or
You can't use
.closest()
on the<img>
tag directly because the img isn't a parent of the.more
object.If this were my code, I'd do it like this because it's the most flexible and the least likely to break if the HTML is edited slightly and you're sure to get the right img object, even if there are more images nearby:
使用parent().siblings()而不是siblings().siblings()
请参阅此处的演示
Use parent().siblings() instead of siblings().siblings()
See demo here
您可以使用常规的类选择器:
You can use a regular class selector: