问题描述
我今天一直在研究我的应用程序的一个小方面,并希望在我的应用程序上获得一个滑动条。今天早上我问了一个问题,那里有一些很好的答案。我最近想试着回答我给出的脚本, CSS 和 HTML 。
I have been working on a small aspect of my application today and wanted to get a sliding bar on my application. I asked a question this morning where there was some good answers. I have recently wanted to try and answer that i ws given using Script, CSS and HTML.
我得到脚本时遇到问题,因为它一直在提示错误:
I am getting to problem to get the Script working as it keeps coming up with an error saying:
0x800a138f - JavaScript runtime error: Unable to get property 'addEventListener' of undefined or null reference
这是脚本:
This is the Script:
<script type="text/javascript">
var desktops = document.querySelectorAll('.desktop');
function hide(element) {
element.style.setProperty('left', '-100%', element.style.getPropertyPriority('left'));
}
function hideAll() {
for (var i = 0; i < desktops.length; i++) {
hide(desktops[i]);
}
}
function show(element) {
element.style.setProperty('left', '0', element.style.getPropertyPriority('left'));
}
document.getElementById('link-one').addEventListener('click', function () {
hideAll();
show(document.getElementById('one'));
}, false);
show(document.getElementById('one'));
</script>
以下是 HTML :
Here is the HTML:
<ul>
<li id="link-one">
<div>1</div>
<div>One</div>
</li>
</ul>
<div id="one" class="desktop">
<h1>Sidebar Example</h1>
<p>This is 1</p>
<p>Something here.</p>
</div>
从我能解决的问题看,它无法找到ID?
From what I can work out its not being able to find the ID?
推荐答案
问题在于,在创建页面上的元素之前,您正在运行脚本。这就是为什么 getElementById
返回 null
。
The problem is that you're running the script BEFORE the elements on the page have been created. That is why the getElementById
is returning null
.
有几种方法可以解决这个问题......
There are several ways to get around this...
- (如Kendall所述),您可以将脚本移动到
< body>
- 您可以将代码放入函数中,并从
< body onload =newFunction();>
- 如果您可以使用jQuery,可以将代码包装在
){...});
- (as commented by Kendall) you can move the script to the end of the
<body>
- You can put your code in a function, and call that function from
<body onload="newFunction();">
- If you can use jQuery, you can wrap the code in
$(function() { ... });
这篇关于无法获取属性'addEventListener'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!