繁体   English   中英

在JQuery中组合parent()和children()选择器

[英]Combining parent() and children() selectors in JQuery

我目前有以下一系列的JQuery选择器:

$(this).parent().parent().children('a').children('img').attr('src')

它工作正常,但是是否有更紧凑的方法来做到这一点?

UPDATE

这是我的HTML结构:

<div class="preview">
    <a><img src="#"></a>
    <div class="info">
        <div class="item">This is where we start.</div>
    <div>
</div>

不管您的具体标记如何,这都可以在您的初始条件下实现:

$(this).parent().siblings('a').children('img').attr('src')

您可以执行以下操作:

$(this).closest('.preview').find('a img').attr('src')

最近的文件 | 查找文件

使用该HTML,一种方法是:

$(this).parents(".preview").find("a img").attr("src");

您还可以轻松地:

$(this).parent().prev().children("img").attr("src");

虽然,如果可以利用HTML5,我的建议是将数据引用添加到start元素div中,如下所示:

<div class="item" data-ref="#imgID-1">This is where we start.</div>
// and of course add an id to the img
<img id="imgID-1" src="blah.png" />

然后,您可以轻松地回忆起:

var source = $($(this).data("ref")).attr("src");

暂无
暂无

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

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