在 JavaScript 中使用 document.getElementById
Use of document.getElementById in JavaScript
有人可以解释一下document.getElementById("demo")
行在下面的示例中的作用吗?
我知道getElementById得到了演示的id,但id是<p id="demo"></p>
<p id="demo"></p>
在这个代码中到底在做什么?
document.getElementById("age")
很清楚,因为它得到了年龄的ID,这是输入。
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 获取元素。但是你必须查看语句的其余部分,以确定代码对该元素到底做了什么:
.innerHTML=voteable;
您可以在此处看到,它将该元素的innerHTML
设置为 voteable
的值。
考虑
var x = document.getElementById("age");
这里x
是带有id="age"
的元素。
现在看下面几行
var age = document.getElementById("age").value;
这意味着您正在获取具有id="age"
行
age=document.getElementById("age").value;
说'我称之为'age'的变量具有id为'age'的元素的值。在本例中为输入字段。
该行
voteable=(age<18)?"Too young":"Old enough";
说在我称为"可投票"的变量中,我按照规则存储值:
"如果年龄未满18岁,则显示'太年轻',否则显示'足够老'"
最后一行告诉将"可投票"的值放在 id 为 'demo' 的元素中(在本例中为 'p' 元素)
document.getElementById("demo").innerHTML = voteable
找到带有 id demo 的元素,然后将voteable
值放入其中;要么太年轻,要么足够老。
如此有效地<p id="demo"></p>
变得例如<p id="demo">Old Enough</p>
代码中,demo
id 您希望在单击事件发生后显示结果,而什么都没有。
你可以拿走任何东西
<p id="demo">
或
<div id="demo">
它只是文档中的节点,您只想在其中显示结果。
> getElementById
使用元素的id
返回对元素的引用。该元素是第一种情况下的input
,第二种情况下是段落。
https://developer.mozilla.org/en-US/docs/Web/API/document.getElementById
只是一个选择器,可帮助您选择特定的标签<p id = 'demo'></p>
元素,这些元素可帮助您在任何情况下(鼠标或键盘)更改行为。
- 正在寻找比$(document).ready慢的$(window).load的替代方案
- document.open/document.write没有正确地清除chrome中的文档——这是chrome的错误吗
- 如何用更合适的内容替换document.write
- document.styleSheets不返回任何内容
- jQuery document.ready not working
- $(document).height()在刷新时随机化值(Safari 5.1.10)
- reactjs this.refs vs document.getElementById
- 如何通过adf中的document.getElementById获取inputText字段值
- window.opener.document在ie中不起作用
- contentWindow.document.body is null
- document.applet.method在Mounatin Lion上抛出safari 6+JDK7异常
- document.getElementById(“st”).click();不起作用
- $(document).height和$(window).heaght都返回相同的值-使用的是正确的doctype
- jQuery document.ready停止代码
- document.getElementById并使用id名称
- 使用jQuery 1.8.1准备好多个$(document).是否有任何开销
- document.getElementById在js中不起作用
- document.getElementById.style.backgroundImage not working
- 停止对document.ready函数的重定向/刷新
- 是否可以 document.getElementsByTagName('head')[0] ever 返回 null