研究一个简单的HTMLElement包装器的想法我偶然发现了Internet Explorer和Chrome的以下内容:
对于DOM树中具有ID的给定HTMLElement,可以使用其ID作为变量名来检索div.所以对于一个喜欢的div
<div id="example">some text</div>
Run Code Online (Sandbox Code Playgroud)
在Internet Explorer 8和Chrome中,您可以执行以下操作:
alert(example.innerHTML); //=> 'some text'
Run Code Online (Sandbox Code Playgroud)
要么
alert(window['example'].innerHTML); //=> 'some text'
Run Code Online (Sandbox Code Playgroud)
那么,这是否意味着DOM树中的每个元素都转换为全局命名空间中的变量?它是否也意味着可以使用它作为getElementById这些浏览器中方法的替代品?
我是javascript的新手,我刚刚发现了一个我从未见过的javascript行为.如果我有一个带有指定id的DOM元素,比如"x",那么在我的javascript中,该元素会自动分配给变量x.我在chrome和safari中看到了这一点.这是javascript的文档功能吗?
例如:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form id='x'>
<input type='text' name='info' id='info'/>
<input type='submit' name='submit' value='Complete'/>
</form>
<script type='text/javascript'>
window.onload = function() {
alert( x==document.getElementById('x') );
info.value = 'Test me!';
}
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
加载后,它会提示为true,输入区域将显示"Test me!".如果这是正确的行为,为什么我们需要document.getElementById呢?
我有以下index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript">
</script>
<script type="text/javascript">
jQuery(document).ready(function($) {
console.log(foo); // jQuery assumes foo is an id?
});
</script>
</head>
<body>
<div id="foo">i'm a div</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
控制台输出:
<div id="foo">i'm a div</div>
为什么?
我刚刚注意到,在 Chrome 中不再需要选择具有 id 的元素,例如 with getElementById,您可以直接使用其名称调用该元素id...例如"para1"在此示例中:
<head>
<title>getElementById Beispiel</title>
<script>
function changeColor(newColor) {
para1.style.color = newColor;
}
</script>
</head>
<body>
<p id="para1">Irgendein Text</p>
<button onclick="changeColor('blue');">Blau</button>
<button onclick="changeColor('red');">Rot</button>
</body>Run Code Online (Sandbox Code Playgroud)
这方面还有更多规范吗?在互联网上没有找到任何有关它的信息..