简体   繁体   中英

Combining parent() and children() selectors in JQuery

I currently have the following series of JQuery selectors:

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

It works just fine but is there a more compact way to do this?

UPDATE

Here's my HTML structure:

<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')

You could do something like:

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

Closest Docs | Find Docs

With that HTML, one way would be:

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

You could also easily:

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

Although, if you can make use of HTML5, my suggestion would be to add a data-ref to the start element div as follows:

<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" />

Then you can easily recall as:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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