簡體   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