从下拉列表中获取值并将其传递给变量

时间:2017-02-03 08:38:48

标签: javascript variables

我刚从编程开始,我就陷入了困境。我在发布之前找到了答案,但我无法理清这段代码。

基本上我想构建一个代码,允许用户选择2个值,然后传递这些值。这是一个足球/足球预测游戏,如果实际得分(var r和z)与预测得分(x和y)匹配,你应该得到3分,如果只有谁获胜是正确的,你得到一个。如果你没有得到正确的分数,但你得到两队之间的目标数差异,你得到2分。这是代码:

<!doctype html>

<html>

<head>
<script type="text/javascript">

var r = 3
var z = 1
var score = 0

var x = document.getElementById("resultHomeTeam").value;
var y = document.getElementById("resultAwayTeam").value;
var f = x-y
var j = r-z

function guru() {

    if(x==r && y==z) {

    score++}

    if(f == j){

    score++}

    if(r<z && x<y){
    score++}

    if(r>z && x>y){
    score++}

    if(r==z && x==y){
    score++

    }

    document.write("your score is " + score)
}



</script>

</head> 

<body>


Juventus
<select id = "resultHomeTeam">
  <option value="0">0</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
  <option value="6">6</option>
  <option value="7">7</option>
  <option value="8">8</option>
  <option value="9">9</option>
</select> 

Milan
 <select id = "resultAwayTeam">
  <option value="0">0</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
  <option value="6">6</option>
  <option value="7">7</option>
  <option value="8">8</option>
  <option value="9">9</option>
</select> 

<input type ="submit" value="submit" onclick =" return guru()"/>

<script type="text/javascript">



</script>



</body>
</html>

1 个答案:

答案 0 :(得分:0)

在函数guru()中声明x和y。并与parseInt()

一起使用

&#13;
&#13;
var score = 0
  var r = 3
var z = 1


function guru() {

  var x = parseInt(document.getElementById("resultHomeTeam").value);
var y = parseInt(document.getElementById("resultAwayTeam").value);
var f = x - y
var j = r - z
  if (x == r && y == z) {
    score++
  }

  if (f == j) {
 console.log('2')
    score++
  }

  if (r < z && x < y) {
    score++
  }

  if (r > z && x > y) {
    score++
  }

  if (r == z && x == y) {
    score++

  }

  document.write("your score is " + score)
}
&#13;
Juventus
<select id="resultHomeTeam">
  <option value="0">0</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
  <option value="6">6</option>
  <option value="7">7</option>
  <option value="8">8</option>
  <option value="9">9</option>
</select>

Milan
<select id="resultAwayTeam">
  <option value="0">0</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
  <option value="6">6</option>
  <option value="7">7</option>
  <option value="8">8</option>
  <option value="9">9</option>
</select>

<input type="submit" value="submit" onclick=" return guru()" />
&#13;
&#13;
&#13;