在函数中插入输入值作为参数不起作用

Inserting input values in function as arguments not working

本文关键字:参数 不起作用 输入 函数 插入      更新时间:2023-09-26

我正试图将从表单中获得的值传递给一个名为Robot()的构造函数;我在控制台中通过自己传递参数来完成这一点没有问题。例如:var travis=新机器人("travis"、"Blue"、"medium");如果我输入travis.speed之类的东西,它会像预期的那样返回1。

但当我尝试在网站上使用我的表格进行测试时,控制台会说Travis没有定义。

我觉得我做的每件事都是正确的,但显然我不是。如果有人能帮助我,我将不胜感激。

我的脚本.js:

var $canvas = $("canvas");
var ctx = $canvas[0].getContext("2d");
function Robot(name, color, robotBuild){
    this.name = name.toLowerCase();
    this.robotBuild = 'medium';
    this.health = 100;
    this.speed = 1;
    this.strength = 1;
    this.powerState = false;
    this.maxStrength = 100;
    this.minStrength = 1;
    this.maxSpeed = 10;
    this.minSpeed = 1;
    this.maxHealth = 100;
    this.minHealth = 0;
    this.points = 0;
    //ROBOT POSITION VALUES
    this.posX = 0;
    this.posY = 0;
    //ROBOT PHYSICAL PROPERTIES
    this.robotWidth = 10;
    this.robotHeight = 10;
    this.robotColor = color.toLowerCase();
}
Robot.prototype.draw = function(){
    ctx.beginPath();
    ctx.rect(this.posX, this.posY, this.robotWidth, this.robotHeight);
    ctx.fillStyle = this.robotColor;
    ctx.fill();
    ctx.closePath();
    this.powerState = true;
};
Robot.prototype.power = function(powerState){
    powerState.toLowerCase();
    if(powerState === "on"){
        this.powerState = true;
    }else if(powerState === "off") {
        this.killRobot();
    }else {
        console.log("Input must be a value of 'on' or 'off'.");
    }
};
Robot.prototype.killRobot = function(){
    this.powerState = false;
    ctx.clearRect(0, 0, $canvas.width, $canvas.height);
    console.log(this.name + " the robot is now dead.");
};
Robot.prototype.setStrength = function(num){
    if( num < this.minStrength || num > this.maxStrength ){
        return 'error: strengthLevel can not be less than 0 or greater than 100.';
    }else if(isNaN(num)){
        return 'error: Input must be a numbered value.';
    }else {
        this.strength = num;
        return this.strength;
    }
};
Robot.prototype.incHealth = function(num){
    if(isNaN(num)){
        console.log('error: Input must be a numbered value.');
    }
    else if((this.health + num) >= this.maxHealth ){
        this.health = 100;
        console.log('You have reached full Health, use it wisely.');
    }else {
        this.health += num;
        console.log('Your Health is increasing.');
        return this.health;
    }
};
Robot.prototype.decHealth = function(num){
    if(isNaN(num)){
        console.log('error: Input must be a numbered value.');
    }
    else if( (this.health - num) <= this.minHealth){
        this.powerState = false;
        this.health = 0;
        this.killRobot();
        return this.health;
    }else {
        this.health -= num;
        console.log('You are loosing health:(');
        return this.health;
    }
};
Robot.prototype.incSpeed = function(num){
    if( (this.speed + num) < this.minSpeed || (this.speed + num) > this.maxSpeed ){
        console.log('error: Speed Level can not be less than 0 or greater than 100.');
    }else if(isNaN(num)){
        console.log('error: Input must be a numbered value.');
    }else {
        this.speed += num;
        return this.speed;
    }
};
Robot.prototype.decSpeed = function(num){
    if( (this.speed - num) < this.minSpeed || (this.speed - num) > this.maxSpeed ){
        console.log('error: Speed Level can not be less than 0 or greater than 100.');
    }else if(isNaN(num)){
        console.log('error: Input must be a numbered value.');
    }else {
        this.speed -= num;
        return this.speed;
    }
};
Robot.prototype.incStrength = function(num){
    if( (this.strength + num) < this.minStrength || (this.strength + num) > this.maxStrength ){
        console.log('error: strengthLevel can not be less than 0 or greater than 100.');
    }else if(isNaN(num)){
        console.log('error: Input must be a numbered value.');
    }else {
        this.strength += num;
        return this.strength;
    }
};
Robot.prototype.decStrength = function(num){
    if( (this.strength - num) < this.minStrength || (this.strength - num) > this.maxStrength ){
        console.log('error: strengthLevel can not be less than 0 or greater than 100.');
    }else if(isNaN(num)){
        console.log('error: Input must be a numbered value.');
    }else {
        this.strength -= num;
        return this.strength;
    }
};
//MOVING ROBOT POSITION FUNCTIONALITY
Robot.prototype.position = function(){
    this.position = {
        posX: this.posX,
        posY: this.posY
    };
    return this.position;
};
Robot.prototype.moveUp = function(y){
    if(this.powerState === true){
        this.posY += y;
        return this.posY;
    }else {
        console.log("Robot is dead and can not move.");
    }
};
$(".createRobot").click(function(){
    $("#robotForm").toggle();
});
$("#submitRobot").click(function(e){
    e.preventDefault();
    var robotName = $("#robotName").val();
    var robotColor = $("#robotColor").val();
    var robotBuild = $("#robotBuild option:selected").text();
    console.log(typeof robotName); // should return "string"
    console.log(robotName + ", " + robotColor + ", " + robotBuild);
    var robot = new Robot(robotName, robotColor, robotBuild);
});

HTML表单:

<div id="robotForm">
   <h4>Create your robot with the form below:</h4>
   <p><label>Your Robot's name:<input class="robotName" type="text" name="name" value="" placeholder="Robot's name"></label></p>
   <p><label>Your Robot's color:<input class="robotColor" type="text" name="color" value="" placeholder="Robot's color"></label></p>
   <p><label>Your Robot's build type:
   <select class="robotBuild" name="robotBuild">
     <span>Select your robot's build type</span>
     <option name="small" value="small">Small Robot Build</option>
     <option name="medium" value="medium">Medium Robot Build</option>
     <option name="large" value="large">Large Robot Build</option>
   </select>
   </label>
   </p>
   <button class="submitRobot" type="submit">Submit your Robot</button>
   </div>

我不知道你想对返回做什么,但我认为这无关紧要。

您必须确保在事件处理程序执行之前执行包含Robot类的代码(即,在jQuery之外的任何程序之前加载JavaScript文件)。

此外,机器人的范围也不正确。我不再使用那种类型的声明,因为它可以做任何事情,但不是你想要的。相反,最好直接将类分配给窗口对象,方法是:

window.Robot = function(...) { ... };

这样,Robot类在全局范围内可用。

Fabian

$(".submitRobot").click(function(e){
    e.preventDefault();
    var robotName = $(".submitRobot").val();
    var robotColor = $(".robotColor").val();
    var robotBuild = $(".robotBuild").val();
    console.log(typeof(robotName));
    console.log(robotName + ", " + robotColor + ", " + robotBuild);
    var robot = new Robot(robotName, robotColor, robotBuild);
    $("#res").html(robot.speed);
	return robot;
	
});
function Robot(name, color, robotBuild){
	
    this.name = name.toLowerCase();
    this.robotBuild = 'medium';
    this.health = 100;
    this.speed = 1;
    this.strength = 1;
    this.powerState = false;
    this.maxStrength = 100;
    this.minStrength = 1;
    this.maxSpeed = 10;
    this.minSpeed = 1;
    this.maxHealth = 100;
    this.minHealth = 0;
    this.points = 0;
    //ROBOT POSITION VALUES
    this.posX = 0;
    this.posY = 0;
    //ROBOT PHYSICAL PROPERTIES
    this.robotWidth = 10;
    this.robotHeight = 10;
    this.robotColor = color.toLowerCase();
	return this;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type=name class='submitRobot' value='Travis'>
<input type=text class='robotColor' value='Blue'>
<input tyle=text class='robotBuild' value='medium'>
<input type=button class='submitRobot' value=submitRobot>
<div id=res></div>

当我运行时,这显示1

您正在使用val()函数从robotName robotColor robotBuild中提取jQuery信息,而您应该使用text()函数。当你试图构建你的对象并从中提取信息时,你最终会得到空白数据,甚至是错误的引用。

Your code works for me.
http://jsfiddle.net/awakeningbyte/2wroeuL2/2/

然而,我注意到你将变量定义为var-travis,而你说"travis没有定义"。这是打字错误吗?

您的函数$(".submitRobot").click(function(e) etc是jQuery
它为类"submitRobot"的所有DOM节点(HTML)添加了一个点击处理程序
每当用户点击这样的DOM节点时,它就会从类"robotName"等的其他DOM节点中获取val()。注意:HTML中可能有不止一个这样的节点,最好使用ID而不是类选择器。

然后它创建一个实体robot,它属于您构建的类Robot。

这里的问题是:

变量Travis不存在(有一个变量robot,而robot.name的字符串内容可能为"Travis"。

可能clickhandler函数不会从表单中获取值,所以robot.name可能是undefined。或者,如果您的clickHandler函数从未被调用,或者从未达到可以创建robot的地步,那么robot可能根本不存在。

如果您在HTML中将class=...更改为id=...,则这可能会起作用:

$("#submitRobot").click(function(e){
    e.preventDefault();
    var robotName = $("#robotName").val();
    var robotColor = $("#robotColor").val();
    var robotBuild = $("#robotBuild option:selected").text();
    console.log(typeof robotName); // should return "string"
    console.log(robotName + ", " + robotColor + ", " + robotBuild);
    var robot = new Robot(robotName, robotColor, robotBuild);
});

更新:var robot的作用域绑定到单击处理程序。所以您不能从控制台访问它,因为控制台在该范围之外。要解决此问题,请在javascript中定义一个全局变量var robot;(global=任何函数或块{}之外的某个位置)
并将点击处理程序的最后一行更改为:

robot = new Robot(robotName, robotColor, robotBuild);

然后,您应该能够从控制台访问robot.name和其他参数。