1

这是我的代码:

html

<html>
<body>
  <div id="id">
    <div class="one">
      <img>
    </div>
    <div class="two">
      <img>
    </div>
    <div class="one">
      <img>
    </div>
  </div>
</body>
</html>

我只想在 div class="one" 内更改图像边距,这是我的 jquery 代码:

$(document).ready(function() {                  
  $(".one").each(function(){
        $("img").css("margin-top", 10 "px");
  });
});

此代码最终会更改所有图像边距,...帮助!

4

1 回答 1

4

您的选择器$("img")匹配所有图像,因此将css其重复应用于它们,每个div.one. 试试这个:

$(document).ready(function() {                  
  $(".one img").css("margin-top", "10px");
});

(我也改为10 "px""10px"但我认为这是问题中的错字。)

$(".one img")使用后代选择器来匹配img属于具有 class 的元素的后代的所有元素"one"

如果您只想匹配直接子代(如您的示例标记),请>改用:

$(document).ready(function() {                  
  $(".one > img").css("margin-top", "10px");
  //      ^--- change is here
});

更多关于选择器:

于 2013-05-31T21:37:45.780 回答