我一直试图抓住DIV的#id并将其传递给每个使用jQuery的孩子无济于事。
<div class="gallery" id="gallery-1">
<a href="link_1">Link 1</a>
<a href="link_2">Link 2</a>
</div>
<div class="gallery" id="gallery-2">
<a href="link_1">Link 1</a>
<a href="link_2">Link 2</a>
</div>
变成..
<div class="gallery" id="gallery-1">
<a ref="gallery-1" href="link_1"><img src="#"/></a>
<a ref="gallery-1" href="link_2"><img src="#"/></a>
</div>
<div class="gallery" id="gallery-2">
<a rel="gallery-2" href="link_3"><img src="#"/></a>
<a rel="gallery-2" href="link_4"><img src="#"/></a>
</div>
我正在使用..
$("div.gallery").each(
function(){
var galleryCount = $("div.gallery");
$("div a:has(img)").attr( "rel", galleryCount );
}
);
..但最终只给了我[object,Object]。它看起来像是在计算div.gallery,并尝试将它们分配给rel。 我如何只获取父ID并将其应用于它的孩子?
答案 0 :(得分:1)
使用以下代码
$(document).ready(function(){
$(".gallery").each(function(){
rel = $(this).attr("id");
$(this).find("a").attr("rel",rel)
});
});
答案 1 :(得分:0)
正确的做法是:
$("div.gallery").each( function()
{
var $this = $(this);
var id = $this.attr('id'); // <-- Get the ID attribute
$this.children("a").attr("rel", id);
});
答案 2 :(得分:0)
这应该有效(未经测试):
$("div.gallery").each(function(){
var galleryId = $(this).attr('id');
$("a:has(img)", this).attr( "rel", galleryId);
}
});
答案 3 :(得分:0)
带孩子,添加rel-attribute,将内部html更改为img。
$(".gallery").children().each(function(){
$(this).attr("rel", $(this).parent().attr("id"));
$(this).html("<img src='#'>");
});
输出:
<div class="gallery" id="gallery-1">
<a ref="gallery-1" href="link_1"><img src="#"/></a>
<a ref="gallery-1" href="link_2"><img src="#"/></a>
</div>
<div class="gallery" id="gallery-2">
<a rel="gallery-2" href="link_3"><img src="#"/></a>
<a rel="gallery-2" href="link_4"><img src="#"/></a>
</div>
答案 4 :(得分:0)
听起来你想将每个父母的id应用于它的孩子的rel属性?尝试:
$('.gallery').each(function () {
$(this).find('a').attr('rel', $(this).attr('id'));
});
这里是 jsFiddle