jquery将对象的数据分配给现有id

时间:2017-08-22 18:44:35

标签: jquery

我有4个带有ID的div: HTML:

<div id="car1">Car 1</div>
<div id="car2">Car 2</div>
<div id="car3">Car 3</div>
<div id="car4">Car 4</div>

<div class="leftCar"></div>
<div class="rightCar"></div>
<button id="button">Race</button>

现在我从4中挑选2到#34;比赛&#34; JS:

// choose a car to compare
$("#car1").on("click", function() {
    $("#car1").appendTo(".leftCar");
});

// choose the other car to compare
$("#car2").on("click", function() {
    $("#car2").appendTo(".rightCar");
});

如何创建对象/ var并将值连接到现有ID以进行比较? 像这样的东西?

var car1 = {"topSpeed":"100","fuel":"50"};
var car2 = {"topSpeed":"80","fuel":"90"};

如何制作汽车&#39;每当我按下按钮Race并且他们的燃油减少(-10)时,最高速度增加(+10)? 另外,如何用燃料= 0来移除/隐藏汽车?

1 个答案:

答案 0 :(得分:1)

此解决方案选项使用数据元素将topSpeed和燃料与每辆车相关联。

&#13;
&#13;
(function(){
  //get the race divs
  var $leftCar = $('.leftCar');
  var $rightCar = $('.rightCar');
  
  //move over any of the left cars
  $('.left-car').on('click', function(){
    if (!$leftCar.children().length) $leftCar.append(this);
  });

  //move over any of the right cars
  $('.right-car').on('click', function(){
    if (!$rightCar.children().length) $rightCar.append(this);
  });
  
  $('#race').on('click', function(){
    //only race if you have two contenders
    if ($leftCar.children().length && $rightCar.children().length) {
      var $car1 = $leftCar.children().eq(0);
      var $car2 = $rightCar.children().eq(0);
      
      //reduce the fuel
      $car1.data('fuel', $car1.data('fuel') - 10);
      $car2.data('fuel', $car2.data('fuel') - 10);
      
      //log the data to see the change
      console.log( $car1.data(), $car2.data() );
      
      //if either of them run out of fuel, remove them
      if ($car1.data('fuel') < 1) $car1.remove();
      if ($car2.data('fuel') < 1) $car2.remove();
    }
  });
})();
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="car1" class="left-car"  data-topspeed="100" data-fuel="60">Car 1</div>
<div id="car2" class="right-car" data-topspeed="90" data-fuel="70">Car 2</div>
<div id="car3" class="left-car"  data-topspeed="120" data-fuel="40">Car 3</div>
<div id="car4" class="right-car" data-topspeed="10" data-fuel="100">Car 4</div>

<hr>
<div class="leftCar"></div>
<div class="rightCar"></div>
<hr>
<button id="race">Race</button>
&#13;
&#13;
&#13;