[英]Combining parent() and children() selectors in JQuery
I currently have the following series of JQuery selectors: 我目前有以下一系列的JQuery选择器:
$(this).parent().parent().children('a').children('img').attr('src')
It works just fine but is there a more compact way to do this? 它工作正常,但是是否有更紧凑的方法来做到这一点?
UPDATE UPDATE
Here's my HTML structure: 这是我的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')
You could do something like: 您可以执行以下操作:
$(this).closest('.preview').find('a img').attr('src')
With that HTML, one way would be: 使用该HTML,一种方法是:
$(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: 虽然,如果可以利用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" />
Then you can easily recall as: 然后,您可以轻松地回忆起:
var source = $($(this).data("ref")).attr("src");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.