简体   繁体   English

选择器不和兄弟姐妹

[英]selectors not and siblings

I have 3 divs and each have one black and red rectangle. 我有3个div,每个div都有一个黑色和红色矩形。 I want that when you click on one of the black rectangles all the reds will change the color to white except the red one that is sibling of the black clicked. 我希望当您单击黑色矩形之一时,所有红色将颜色更改为白色,但红色是与单击的黑色同胞的红色。 I don't want to add any more classes ids or change the dom. 我不想添加任何其他类ID或更改dom。 I've been trying with no success. 我一直尝试都没有成功。 thx in advanced. 先进的。

  $(document).ready(function(){ $(".black-rectangle").click(function(){ $(".red-rectangle").not(this.siblings(".rec2")).css("background-color","#fff"); }) }) 
  .black-rectangle{ height: 50px; width: 50px; background-color:#000; border: 5px solid green; margin-top: 10px; } .red-rectangle{ height: 50px; width: 50px; background-color: red; border: 5px solid green; margin-top: 10px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <body> <div> <div class="black-rectangle"></div> <div class="red-rectangle"</div> </div> <div> <div class="black-rectangle"></div> <div class="red-rectangle"</div> </div> <div> <div class="black-rectangle"></div> <div class="red-rectangle"</div> </div> </body> 

siblings is a jQuery method, but this is a DOM element, not a jQuery object. siblings是一个jQuery方法,但是this是一个DOM元素,而不是一个jQuery对象。 You need to use $(this) to wrap it in a jQuery object. 您需要使用$(this)将其包装在jQuery对象中。

There's no rec2 class in your HTML, so I changed it to just .siblings() with no selector. 您的HTML中没有rec2类,因此我将其更改为仅带选择器的.siblings()

 $(document).ready(function() { $(".black-rectangle").click(function() { var $this = $(this); $(".red-rectangle").not($this.siblings()).css("background-color", "#fff"); }) }) 
 .black-rectangle { height: 50px; width: 50px; background-color: #000; border: 5px solid green; margin-top: 10px; } .red-rectangle { height: 50px; width: 50px; background-color: red; border: 5px solid green; margin-top: 10px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <body> <div> <div class="black-rectangle"></div> <div class="red-rectangle"></div> </div> <div> <div class="black-rectangle"></div> <div class="red-rectangle"></div> </div> <div> <div class="black-rectangle"></div> <div class="red-rectangle"></div> </div> </body> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM