成功添加了事件侦听器,如果使用move_box功能中的菜单[1]或菜单[0]替换menu [i]按钮功能。当我点击一个按钮时,我收到此错误:未捕获无法补间空目标。我认为它与"这个"的上下文有关。在函数move_box中。我在JSFiddle http://jsfiddle.net/jimeast123/F4WkU/1/
上有这个<script src="http://cdnjs.cloudflare.com/ajax/libs/gsap/latest/TweenMax.min.js"></script>
<style type="text/css">
.box {
margin: 0px;
height: 50px;
width: 50px;
background-color: blue;
}
li {list-style: none;}
.inner {margin-left: -40px; display: block;}
.inner li, .box {display: block;}
#outer li { display: inline-block;}
</style>
</head>
<body>
<ul id="outer">
<li><button type="button" class="toggle" name="btn1">Open</button>
<ul class="inner">
<li><div class="box"></div></li>
</ul>
</li><!-- end of outer li -->
<li><button type="button" class="toggle" name="btn2">Open</button>
<ul class="inner">
<li><div class="box"></div></li>
</ul>
</li> <!-- end of outer li -->
</ul> <!-- end of outer -->
<script>
var menu = document.getElementsByClassName('box');
var btn = document.getElementsByClassName('toggle');
function move_box(e) {
if(this.innerHTML === 'Open') {
TweenLite.to(menu[i], 2, {y: 100, ease:Power2.easeOut});
this.innerHTML = 'Close';
} else {
TweenLite.to(menu[i], 2, {y: 0, ease:Power2.easeOut});
this.innerHTML = 'Open';
}
}
for (var i = 0; i < btn.length; i++ ) {
btn[i].addEventListener("click", move_box, false);
}
</script>
</body>
答案 0 :(得分:0)
变量&#34; i&#34;在函数被调用时没有定义,因为它是循环的一部分。你能做的就是使用&#34;这个&#34;找到数组中按钮的索引,然后获取相同索引的菜单。以下代码未经测试,但我认为它可行:
TweenLite.to(menu[btn.indexOf(this)], 2, {y: 100, ease:Power2.easeOut});
如果这不正确,我认为它至少会指出你正确的方向。
编辑:
以下代码有效。通过导航DOM来查找相关框,需要采用不同的方法。
var btn = document.getElementsByClassName('toggle');
function move_box(e) {
if (this.innerHTML === 'Open') {
TweenLite.to(this.parentNode.getElementsByClassName('box')[0], 2, { y: 100, ease: Power2.easeOut });
this.innerHTML = 'Close';
} else {
TweenLite.to(this.parentNode.getElementsByClassName('box')[0], 2, { y: 0, ease: Power2.easeOut });
this.innerHTML = 'Open';
}
}
for (var i = 0; i < btn.length; i++) {
btn[i].addEventListener("click", move_box, false);
}
答案 1 :(得分:0)
我发现了一个修复我首先在btn中设置了一个id btn + i然后在事件处理程序中我使用getAttribute来重新获取id然后使用substr方法分隔出最后的数字如果id我然后将该数字赋给变量j,然后使用j作为菜单数组的数组索引。这是剧本:
<script>
var i;
var menu = document.getElementsByClassName('box');
var btn = document.getElementsByClassName('toggle');
function move_box(e) {
var j;
var id = this.getAttribute("id");
j = id.substr(3,1); //get digit at end of id.
if(this.innerHTML === 'Open') {
TweenLite.to(menu[j], 2, {y: 100, ease:Power2.easeOut});
this.innerHTML = 'Close';
} else {
TweenLite.to(menu[j], 2, {y: 0, ease:Power2.easeOut});
this.innerHTML = 'Open';
}
}
for ( i = 0; i < btn.length; i++ ) {
btn[i].addEventListener("click", move_box, false);
btn[i].setAttribute("id", "btn" + i);
}
</script>