我在下面的代码中遇到了一些问题:
HTML:
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Untitled</title>
</head>
<body>
<div id="wrapper">
<div id='one'>
<h1>
Title
<a href="#">view all</a>
</h1>
</div>
<div id='two'>
<h1>
Title
<a href="#">view all</a>
</h1>
</div>
<div id='three'>
<h1>
Title
<a href="#">view all</a>
</h1>
</div>
</div>
</body>
</html>
JavaScript的:
var selector = $("#one a, #two a, #three a");
selector.each(function() {
$(this).after("<span class='viewAll'>All</span>").hover(mouseIn, mouseOut);
function mouseIn() {
span = $(this).next("span");
console.log(span.length)
span.show('slide', {direction: 'right'});
}
function mouseOut() {
span = $(this).next("span");
console.log(span.length)
span.hide();
}
});
$("span").css({'float' : 'right', 'margin-right' : '10px'}).hide();
CSS:
#wrapper {
width:960px;
margin:0 auto;
}
h1 {
background:#e1e1e1;
padding:10px;
margin-bottom:20px;
}
a {
background: url(http://lorempixum.com/15/15/) no-repeat;
text-indent:-9000px;
display:block;
width:15px;
height:15px;
float:right;
}
当我将鼠标悬停在锚标记上时,JavaScript应该使用选择器找到它,然后在其后面定位跨度。然后它应该在鼠标悬停时将隐藏的span标记向左滑动.show('slide', {direction: 'right'});
,并在鼠标移开时隐藏它。
现在,问题是当我使用上面的行显示垃圾邮件时,选择有时会变回空白。但如果我只是简单地使用.show()
就没有问题,那么它总会以一个跨度的形式返回。
我使用添加了console.log(span.length)
行来表明它经常返回0
。如果我使用.show()
,它将再次返回1
有谁知道这里发生了什么?
答案 0 :(得分:0)
不确定我是怎么做的但是......我认为这就是你要找的东西:http://jsfiddle.net/3Ws3w/72/
正如user828584所说,是的,我猜它源于在匿名函数中使用$(this)。
答案 1 :(得分:0)
我能够通过直接将跨度传递给处理程序来获得跨度。我不确定为什么在动画期间无法选择范围。
var selector = $("#one a, #two a, #three a");
selector.each(function() {
var jqSpan = $("<span class='viewAll'>All</span>");
$(this).after(jqSpan)
.mouseover({the_span : jqSpan}, mouseIn)
.mouseout({the_span : jqSpan}, mouseOut);
function mouseIn(event) {
event.data.the_span.stop(true, false).show('slide', {direction: 'right'});
}
function mouseOut(event) {
event.data.the_span.stop(true, true).hide();
}
});
$("span").css({'float' : 'right', 'margin-right' : '10px'}).hide();
答案 2 :(得分:0)
我想这是因为你使用了这个关键字而没有绑定它。
在你的mousein / out函数中,this关键字没有引用正确的对象
试试这个:
$(this).after("<span class='viewAll'>All</span>").hover($.proxy(mouseIn, this), $.proxy(mouseOut, this));