使用构造函数 - 原型从文本框输出值

Output values from Textbox using Constructor - Prototype

本文关键字:文本 输出 原型 构造函数      更新时间:2023-09-26

我正在尝试在单击按钮(John)时在文本框中输出插入的值。目前我刚刚添加了默认值在这里(约翰=新球员(30,"英格兰",3));但我希望从文本框中选择这些值。请告知我将如何去做。我尝试从文本框中获取值并分配给变量(x,y,z 在脚本中注释掉)并传递到这里( John= 新玩家(x,y,z));但它似乎不起作用。

Age : <input type = "text" id = "test1" /><br>
County : <input type = "text" id = "test2" /><br>
Rank: <input type = "text" id = "test3" /><br>
<button type="button" onclick="John.myPlayer()">John</button>
<br>
<br>
<div id = "box"></div>
<br>

<script type="text/javascript">
// var x = document.getElementById('test1').value;
// var y = document.getElementById('test2').value;
// var z = document.getElementById('test3').value);
function Player(a,c,r){
this.age=a;
this.country=c;
this.rank=r;
}
Player.prototype.myPlayer = function(){
document.getElementById('box').innerHTML = "John is from " + this.country + " he is       " + this.age + " years old and his rank is " + this.rank;
}
John= new Player(30,"England",3);
John.myPlayer()

</script>

我的建议是创建一个在 onclick 事件上调用的函数,并从那里的文本框中读取值,然后创建一个新的 Player 实例。

<button type="button" onclick="createNewPlayer()">John</button>

在 JavaScript 中:

function createNewPlayer() {
  var x = document.getElementById('test1').value;
  var y = document.getElementById('test2').value;
  var z = document.getElementById('test3').value);
  John= new Player(x, y, z);
  John.myPlayer()
}

请像这样尝试。

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript">
    function show(){
        var age = document.getElementById('test1').value;
        var country = document.getElementById('test2').value;
        var rank = document.getElementById('test3').value;
        John = new Player(age, country, rank);
        John.myPlayer();
    }
    Player.prototype.myPlayer = function() {
        var output = "John is from " + this.country + " he is " + this.age + " years old and his rank is " + this.rank;
        document.getElementById('box').innerHTML = output;
}
    function Player(a,c,r){
        this.age=a;
        this.country=c;
        this.rank=r;
    }
    </script>
</head>
<body>
    Age : <input type = "text" id = "test1" /><br>
    County : <input type = "text" id = "test2" /><br>
    Rank: <input type = "text" id = "test3" /><br>
    <div id="box">
    </div>
    <button type="button" onclick="show()">John</button>
</body>
</html>