查看其他帖子的一些内容,找到我需要的代码,但不能完全按照我的要求去做。
我想根据图片的alt标签向父元素添加一个类。
所以从这个:
<div class="img-wrap">
<div class="img-icon">
<a href="">
<img alt="home" />
</a>
</div>
</div>
对此:
<div class="img-wrap home">
<div class="img-icon">
<a href="">
<img alt="home" />
</a>
</div>
</div>
这是我正在使用的代码:
$('img').each(function() {
$(this).parent().addClass( $(this).attr('alt') );
});
虽然这会添加所需的类,但它会将其添加到“a”中...但是我希望它添加到#img-wrap中。我怎么能这样做?
答案 0 :(得分:3)
ID应该是唯一的..您不应该像这样复制ID。尝试将其更改为课程class="img-wrap"
并查看以下代码。
<强> HTML:强>
<div class="img-wrap">
<div class="img-icon">
<a href="">
<img alt="home" />
</a>
</div>
</div>
<强>代码:强>
$('img').each(function () {
$(this).closest('.img-wrap').addClass(this.alt);
});
答案 1 :(得分:1)
$('img').each(function() {
$(this).parents('#img-wrap').addClass( $(this).attr('alt') );
});
OR
$('img').each(function() {
$(this).parent().parent().parent().addClass( $(this).attr('alt') );
});
//to make it more obvious why it is not selecting the #img-wrap <div>
是的,#ID只能使用一次,如果重复使用,则使用类
答案 2 :(得分:0)
使用.closest()选择所需的父元素 http://api.jquery.com/closest/
答案 3 :(得分:0)
尝试使用.closest()
请注意,HTML页面中的 Id 应该是唯一的。尝试为div提供类而不是 ID
$('img').each(function() {
$(this).closest('.img-wrap').addClass( $(this).attr('alt') );
});
<div class="img-wrap">
<div class="img-icon">
<a href="">
<img alt="home" />
</a>
</div>