在JavaScript中使用document.getElementById [英] Use of document.getElementById in JavaScript

查看:62
本文介绍了在JavaScript中使用document.getElementById的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的示例中,有人可以解释document.getElementById("demo")行是什么吗?

Can someone explain what the document.getElementById("demo") line does in the example below?

我了解getElementById获取了demo的ID,但ID为<p id="demo"></p> <p id="demo"></p>在此代码中到底在做什么?

I understand getElementById gets the id of demo but the id is <p id="demo"></p> What exactly is <p id="demo"></p> doing in this code?

document.getElementById("age")很清楚,因为它获得了年龄ID作为输入.

document.getElementById("age") is clear as it gets the id of age which is the input.

function myFunction() {
  var age,voteable;
  age = document.getElementById("age").value;
  voteable = (age < 18)? "Too young" : "Old enough";
  document.getElementById("demo").innerHTML = voteable;
}

<p>Click the button to check the age.</p>

Age:<input id="age" value="18" />
<p>Old enough to vote?</p>
<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

推荐答案

您是正确的,因为document.getElementById("demo")调用会通过指定的ID为您获取元素.但是您必须查看语句的其余部分,以弄清楚代码对该元素的确切作用:

You're correct in that the document.getElementById("demo") call gets you the element by the specified ID. But you have to look at the rest of the statement to figure out what exactly the code is doing with that element:

.innerHTML=voteable;

您可以在此处看到将元素的innerHTML设置为voteable的值.

You can see here that it's setting the innerHTML of that element to the value of voteable.

这篇关于在JavaScript中使用document.getElementById的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆