【问题标题】:Inserting input values in function as arguments not working在函数中插入输入值作为参数不起作用
【发布时间】:2016-01-31 08:20:00
【问题描述】:

我正在尝试将从表单中获得的值传递给名为 Robot() 的构造函数;通过自己传入参数,我可以在控制台中完成此操作。 例如: var travis = new Robot("Travis","Blue","medium"); 如果我要输入类似 travis.speed 的内容,它将按预期返回 1。

但是当我尝试在网站上使用我的表单并对其进行测试时,控制台显示 Travis 未定义。

我觉得我做的一切都是正确的,但显然我不是。如果有人可以请帮助我,我将不胜感激。

我的 script.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>

【问题讨论】:

  • 您希望return robot; 实际返回到什么位置?未定义的日志记录在哪里?
  • 向我们展示您的测试,因为问题是在您的点击事件中,您将机器人实例返回到无处。
  • 您实际上并没有在这里测试您的机器人对象,您应该尝试执行类似console.log(robot.name) 的操作,看看会发生什么。
  • Travis 没有定义,因为你没有定义它(至少没有在你发布的代码中)。也许使用Travis = new Robot(...) 而不是var robot = ...
  • 您正在事件侦听器范围内创建 Robot 实例。如果您想在事件侦听器之外使用它,请在外部范围内定义一个变量并将实例分配给它,或者直接使用window.robot1 = new Robot()

标签: javascript jquery


【解决方案1】:

$(".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

【讨论】:

  • 我看到它在 DOM 中放置了正确的响应,为什么我不能在控制台中输入 robots.speed 并获得相同的响应,而没有它说没有定义机器人?我是在尝试做一些超出范围的事情吗?
  • 在构造函数中添加return了吗?
  • 哈哈,我看到你添加了它,我确实将它添加到我的脚本中。谢谢你指出这一点。我最终在构造函数的底部添加了 return this 以及添加了 var robots;在我的脚本顶部,使其成为一个全局变量。现在可以了。
【解决方案2】:

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

【讨论】:

  • 这适用于从&lt;Select&gt; 组件内的选项中获取文本(innerHTML),但.val() 对于从&lt;input type="text"&gt; 组件获取用户输入是有效的。
  • @wintvelt 我刚刚注意到他编辑了他的帖子,所以当他编辑我们的答案可能变得无关紧要的东西时:-/
  • 刚刚经历了同样的事情;)
【解决方案3】:

我不知道你想对退货做什么,但我认为没关系。

您必须确保在事件处理程序执行之前执行包含您的机器人类的代码(即通过在除 jQuery 之外的任何其他文件之前加载 JavaScript 文件)。

另外,Robot 的范围也不正确。我不再使用那种类型的声明,因为它做了所有事情,但不是你想要的。相反,最好将类直接分配给窗口对象,方法是:

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

这样,Robot 类是全局可用的。

法比安

【讨论】:

  • 我发现了问题所在。我的变量机器人仅在提交函数的范围内,而不是全局范围内。因此,当我在控制台中键入 robots.speed 时,它没有被定义,因为它不在全局范围内。谢谢。虽然我没有使用 window.function 我只是在脚本顶部创建了机器人变量,所以它是全局的。
【解决方案4】:

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

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

这里的问题是:

变量Travis不存在(有一个变量robot,而robot.name可以有“Travis”的字符串内容。

并且可能 clickhandler 函数不会从您的表单中获取值,因此 robot.name 可能是 undefined。 或者 robot 甚至不存在,如果您的 clickHandler 函数永远不会被调用,或者永远不会达到可以创建 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 范围绑定到 clickhandler。因此,您无法从控制台访问它,因为控制台超出了该范围。要解决此问题,请在您的 javascript 中定义一个全局变量 var robot;(全局 = 任何函数或块 {} 之外的某个位置)。
并将点击处理程序的最后一行更改为:

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

那么您应该可以从您的控制台访问robot.name 和其他参数。

【讨论】:

  • 我编辑了我的评论以显示我的 HTML 表单。希望这会有所帮助。
  • 如果这将有助于解释我想要做什么,我可以分享我的其余 javascript 代码。这个项目的全部目的是更好地理解对象继承和原型。
  • 我想用 Canvas 和 javascript 创建一个简单的游戏。
  • 我尝试了您所做的功能编辑以及将我的输入更改为 ID,当我在控制台中键入 robots.speed 时显示未定义
  • @TravisMichaelHeller 这个问题与@fabian 的回答有关:var robot 是范围绑定到点击处理程序的。因此,您无法从控制台访问它,因为控制台超出了该范围。见编辑。
【解决方案5】:
Your code works for me.
http://jsfiddle.net/awakeningbyte/2wroeuL2/2/

但是,我注意到您将变量定义为 var travis,而您却说“未定义 Travis”。这是笔误吗?

【讨论】:

    猜你喜欢
    • 2020-07-27
    • 2014-12-31
    • 2021-06-12
    • 1970-01-01
    • 1970-01-01
    • 2011-12-21
    • 2016-02-16
    • 1970-01-01
    • 2021-11-10
    相关资源
    最近更新 更多