简体   繁体   English

在jQuery中选择同级的同级

[英]Select siblings of siblings in jQuery

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. 在下面的代码,当用户点击了在'.more'跨度元件,我想检索来自信息(例如,ID) img的内article使用jQuery标签。

Here's the HTML: 这是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! 非常感谢!

You can do that like this: 您可以这样做:

$(".more").click(function() {
    var id = $(this).closest("article").find("img:first").attr("id");
});

This looks up the parent tree for the containing <article> tag. 这会在父树中查找包含<article>标签的标签。 Then, it finds the first <img> tag in that and gets its id value. 然后,它在其中找到第一个<img>标记并获取其id值。

You can't use .siblings() on $(this) because the image isn't a direct sibling of $(this) . 您不能在$(this) .siblings()上使用.siblings() ,因为图像不是$(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. 如果您拥有img是其兄弟姐妹的正确父级,则可以使用.siblings() ,但这比我建议的脆弱得多。 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: 例如,这也可以,但是它依赖于HTML对象的更精确定位,任何细微的编辑都可能破坏此代码:

$(".more").click(function() {
    var id = $(this).parent().prev().attr("id");
});

or 要么

$(".more").click(function() {
    var id = $(this).parent().siblings("img").attr("id");
});

You can't use .closest() on the <img> tag directly because the img isn't a parent of the .more object. 您不能直接在<img>标记上使用.closest() ,因为img不是.more对象的父代。

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: 如果这是我的代码,我会这样做,因为如果对HTML进行少量编辑,它是最灵活且最不可能破坏的,即使附近有更多图片,您也可以确保获得正确的img对象:

<article>
<img class="target" src="..." id="TR"/>
<div>some text <a>link</a> <span class="more">read more</span></div>
</article>

$(".more").click(function() {
    var id = $(this).closest("article").find(".target").attr("id");
});

Use parent().siblings() instead of siblings().siblings() 使用parent()。siblings()而不是siblings()。siblings()

$('.more').click(function () { 
    var left = $(this).parent().siblings('img').attr('id');
    alert(left);
});

See demo here 在此处查看演示

您可以使用常规的类选择器:

$('article > img[id]').attr('id');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM