我想做一个树问题而且我这样做并且它有效,但我想知道是否有更简单的方法来做它?

时间:2017-09-25 17:55:47

标签: javascript html css

这是树问题,它是我想要做的简单示例,底部是保存单选按钮值的段落



function radioFunc(answer) {
  document.getElementById("radio").innerHTML = answer;
}


function question1() {
  var myanswer = document.getElementById("radio").innerHTML;
  if (myanswer === "yes") {
    document.getElementById("div1").style.display = "none";
    document.getElementById("div2").style.display = "block";
  } else if (myanswer === "no") {
    alert("I'm sorry , You're not Ramy!");
  }
}

<div id="div1">
  <p>Are you 18?</p>
  <form>
    <input type="radio" name="answer" value="yes" onclick="radioFunc(this.value)">Yes<br>
    <input type="radio" name="answer" value="no" onclick="radioFunc(this.value)">No<br><br>
    <input type="button" value="confirm" onclick="question1()">
  </form>
</div>
<div id="div2" style="display: none;">
  <p>Are you over in college?</p>
  <form>
    <input type="radio" name="answer" value="yes" onclick="radioFunc(this.value)">Yes<br>
    <input type="radio" name="answer" value="no" onclick="radioFunc(this.value)">No<br><br>
    <input type="button" value="confirm" onclick="question2()">
  </form>
</div>

<p id="radio" style="display: none;"></p>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

你的逻辑看起来很好,但你可以使用单一功能问题()而不是制作如此多的函数question1(),question2()这将使你的javascript代码看起来更简单,更容易(假设在你提出的任何问题中答案都是肯定的“我很抱歉,你不是拉米!”)

<div id="div1">
    <p>Are you 18?</p>
    <form>
        <input type="radio" name="answer" value="yes" 
        onclick="radioFunc(this.value)">Yes<br>
        <input type="radio" name="answer" value="no" 
        onclick="radioFunc(this.value)">No<br><br>
        <input type="button" value="confirm" onclick="question()">
    </form>
    </div>
    <div id="div2" style="display: none;">
    <p>Are you over in college?</p>
    <form>
        <input type="radio" name="answer" value="yes" 
          onclick="radioFunc(this.value)">Yes<br>
        <input type="radio" name="answer" value="no" 
          onclick="radioFunc(this.value)">No<br><br>
        <input type="button" value="confirm" onclick="question()">
    </form>
    </div>
    <div id="div3" style="display: none;">
        <h1>Hello Ramsey<h1>
    </div>

<p id="radio" style="display: none;"></p>

javascript代码:

function radioFunc(answer){
    document.getElementById("radio").innerHTML = answer;
}

var count = 1;
var quesToHide='';
var quesToShow='';
function question() {
    var myanswer = document.getElementById("radio").innerHTML;
    if (myanswer === "yes") {
        quesToHide ="div"+count;
        count++;
        quesToShow ="div"+count;
        document.getElementById(quesToHide).style.display = "none";
        document.getElementById(quesToShow).style.display = "block";
    } else if(myanswer === "no"){
        alert("I'm sorry , You're not Ramy!");
    }
}