Проблема здесь:
$("#startM").css("background", "green").attr("disabled",false);
$("#stopM").css("background", "grey").attr("disabled",true);
var starting=function(){
setInterval(carMoving,5);
$("#startM").css("background", "grey").attr("disabled",true);
$("#stopM").css("background", "red").attr("disabled",false);
}
var carId=starting;
var stop=function(){
clearInterval(carId);
}
$("#stopM").click(function(){
clearInterval(carId);
});
$("#startM").click(starting);
Это работает:
$("#startM").click(starting);
А это никак:
$("#stopM").click(function(){
clearInterval(carId);
});
Весь код, если нужно:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Cars</title>
</head>
<body>
<button id="startM">START!</button>
<button id="stopM">STOP!</button>
<script src="https://code.jquery.com/jquery-2.1.0.js"></script>
<script>
var Car=function (x, y){
this.x=x;
this.y=y;
this.draw();
};
Car.prototype.draw=function(){
var carHtml='<img width="100" src="../BMW_Car_PNG_VectorForFree.jpg">';
this.carElement=$(carHtml);
this.carElement.css({
position: "absolute",
left: this.x,
top: this.y
});
$("body").append(this.carElement);
};
Car.prototype.moveRight=function(distance){
this.x+=distance;
this.carElement.css({
left: this.x,
top: this.y
});
};
var tesla=new Car(0, 130);
var nissan =new Car (0, 230);
var ford=new Car(0, 330);
var tesla1=new Car(0, 430);
var nissan1 =new Car (0, 530);
var ford1=new Car(0, 630);
var carMoving=function(){
tesla.moveRight(Math.random()*2);
nissan.moveRight(Math.random()*2);
ford.moveRight(Math.random()*2);
tesla1.moveRight(Math.random()*2);
nissan1.moveRight(Math.random()*2);
ford1.moveRight(Math.random()*2);
};
$("#startM").css("background", "green").attr("disabled",false);
$("#stopM").css("background", "grey").attr("disabled",true);
var starting=function(){
setInterval(carMoving,5);
$("#startM").css("background", "grey").attr("disabled",true);
$("#stopM").css("background", "red").attr("disabled",false);
}
var carId=starting;
var stop=function(){
clearInterval(carId);
}
$("#stopM").click(function(){
clearInterval(carId);
});
$("#startM").click(starting);
</script>
</body>
</html>