我无法正确获得价值

时间:2019-10-12 14:18:23

标签: jquery html css

我是新手。请帮我。我无法获得黑色立方体的真实价值。

<html>
<head>
  <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
</head>
<div style="background-color:blue;" class="color-item"></div>
<div style="background-color:black;" class="color-item"></div>
<style>
  .color-item {
    width: 30px;
    height: 30px;
    float: left;
    margin: 0 0px;
    border: 1px solid #ddd;
    cursor: pointer;
    position: relative;
  }
</style>
<script>
  $('.color-item').click(function() {
    var color = $('.color-item').css('background-color');
    console.log(color.toString());
  });
</script>
</html>

1 个答案:

答案 0 :(得分:1)

您应该在函数正文中使用$(this)代替$('。color-item'):

<html>
<head>
  <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
</head>
<div style="background-color:blue;" class="color-item"></div>
<div style="background-color:black;" class="color-item"></div>
<style>
  .color-item {
    width: 30px;
    height: 30px;
    float: left;
    margin: 0 0px;
    border: 1px solid #ddd;
    cursor: pointer;
    position: relative;
  }
</style>
<script>
  $('.color-item').click(function() {
    var color = $(this).css('background-color');
    console.log(color.toString());
  });
</script>
</html>