为div中的所有imgs赋予属性

时间:2012-11-26 12:08:40

标签: jquery children

我希望div中的所有图像都有一定的边距属性,我似乎无法让它工作,这就是我尝试过的,

$("#images > img").each(function(){
    $(img).css({
      margin-top:15px;
      margin-bottom:15px;
});
});

感谢您的帮助

$("#pt_figures").click(function() {

$('#images').empty();

$('#images').css({
paddingLeft: 150,
paddingRight: 0
});
$('#controls').css({
width:700,
marginLeft:150
});
$('#info').css({
width:660,
marginLeft:150

});

var id = $(this).attr('id');

$(“#info_header”)。load(id +“_ header.txt”);    $(“#content_1”)。load(id +“_ 1.txt”);    $(“#content_2”)。load(id +“_ 2.txt”);    $(“#content_3”)。load(id +“_ 3.txt”);

$("<img>", { src: "http://www.klossal.com/figures_doc.jpg" }).appendTo("#images"); 
$("<img>", { src: "http://www.klossal.com/figure_front.png" }).appendTo("#images"); 
$("<img>", { src: "http://www.klossal.com/figure_back.jpg" }).appendTo("#images");


$("#images img").addClass("images");

$("#top_section").animate({
    height: 3780
}, 300);
$("#grid").animate({
    marginTop: 3780 + 300,
    paddingBottom: 300
}, 300); 


});

6 个答案:

答案 0 :(得分:4)

使用$(this)

 $("#images > img").each(function(){
        $(this).css({
          margin-top:15px;
          margin-bottom:15px;
    });
    });

答案 1 :(得分:2)

建议的做法肯定是添加一个定义所需属性的类,而不是直接在jQuery代码中编写CSS。

<强>使用Javascript:

$("#images img").addClass("myClass");

<强> CSS:

.myClass {
   margin:15px 0;
}

或者,只需在CSS中定义属性,不要使用jQuery。

<强> CSS:

#images img {
   margin:15px 0;
}

答案 2 :(得分:1)

$("#images > img").each(function(){
    $(this).css({
      margin-top:15px;
      margin-bottom:15px;
});
});

答案 3 :(得分:1)

试试这个:

$("#images img").each(function(){
    $(this).css({
        margin-top:15px;
        margin-bottom:15px;
    });
});

您正在使用$(img)但没有上下文。请改用$(this)。我也删除了&gt;来自你的选择器,以防IMG标签不是DIV的直接后代。

答案 4 :(得分:1)

这也可以在纯粹的CSS中完成。

#images > img { // ">" means direct child, remove it if necesarry
  margin: 15px 0; // shorthand for top/bottom: 15px and right/left: 0px
}

>表示直接子女,这意味着只有#images儿童的图像才会受到影响,“孙子”才会受到影响,而且不会受到影响。如果您打算让他们受到影响,请删除>

答案 5 :(得分:0)

$(img)更改为$(this),应该不错。

$(this)是每个循环中的当前对象。

你也可以申请$("#images > img").css(...),因为我没有直接看到为什么你需要循环使用它们。