0

单击按钮(John)时,我试图在文本框中输出插入的值。目前我刚刚在这里添加了默认值(John= new Player(30,"England",3)); 但我希望从文本框中选择这些值。请告知我将如何去做。我尝试从文本框中获取值并分配给变量(x,y,z在脚本中注释掉)并在此处传递(John = new Player(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>
4

2 回答 2

0

我的建议是创建一个在 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()
}
于 2012-08-17T11:43:09.923 回答
0

请像这样尝试..

<!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>
于 2012-08-17T11:48:32.050 回答