如何将语句从警报更改为文本

时间:2015-09-05 05:04:10

标签: javascript input

我如何将if语句作为警报出现,让它在我的页面上显示为文本。感谢

 document.getElementById("button").onclick=function() {

        if (document.getElementById("ask").value=="how tall are the pyramids") {

            alert ("146.5 meters");

            } else if (document.getElementById("ask").value == "how tall is the gateway arch") {

alert("630 feet");

         } else if (document.getElementById("ask").value == "how tall is the empire state building") {

         alert("6900 feet");

3 个答案:

答案 0 :(得分:1)

我可能误解了,但听起来你想在html元素中显示值而不是警告值。见下面的例子

document.getElementById("button").onclick = function() {
  var val = document.getElementById("ask").value;
  var answer = "I don't know!";
  if (val == "how tall are the pyramids")
    answer = "146.5 meters";
  else if (val == "how tall is the gateway arch")
    answer = "630 feet";
  else if (val == "how tall is the empire state building")
    answer = "6900 feet";
  document.getElementById("answer").innerHTML = answer;
}

在html中,添加一个像这样的答案元素

<p id="answer"></p>

请参阅CodePen

答案 1 :(得分:1)

您想在页面中添加另一个可以显示结果的元素。

在下面的演示中,我添加了span元素,并将id属性设置为answer

document.getElementById("button").onclick=function(){
var Q = document.getElementById("ask").value;
var A = document.getElementById("answer");
var Result = "Ask another?";
  if (Q=="how tall are the pyramids"){
    Result="146.5 meters";
  }else if(Q=="how tall is the gateway arch"){
    Result="630 feet";
  }else if(Q == "how tall is the empire state building"){
    Result="6900 feet";
  }
  A.innerHTML = Result;
}
<span id="answer"></span><br/>
<input type="text" id="ask" />
<button type="button" id="button">Ask</button>

如果您不理解上述任何源代码,请在下面留言。

我希望这会有所帮助。快乐的编码!

答案 2 :(得分:0)

变化

 document.getElementById("ask").value

document.getElementById("ask").innerHTML

document.getElementById("ask").innerText