这是什么正确的语法?
问题描述:
当我将鼠标放在它们上面时,我试图在现有图像上淡出图像,而无需为每个图像重新编写相同的功能。这是什么正确的语法?
目前我有:
<script type="text/javascript">
$(document).ready(function() {
$('.image').mouseenter(function() { //fade in hover image
$(this.getAttribute("name")).fadeIn(500);
});
$('.hoverimage').mouseout(function() { //fade out hover image
$(this).fadeOut(500);
});
});
</script>
...
...
<!--base images-->
<img src="image1.png" class="image" name="hoverimage1">
<img src="image2.png" class="image" name="hoverimage2">
<img src="image3.png" class="image" name="hoverimage3">
<!--image to appear when hovering over-->
<img src="image1_glow.png" class="hoverimage" id="hoverimage1">
<img src="image2_glow.png" class="hoverimage" id="hoverimage2">
<img src="image3_glow.png" class="hoverimage" id="hoverimage3">
假设CSS已经有这么悬停图像被放置在基本图像的顶部。我的代码试图做的是:
- 当鼠标进入的“image1.png”分区,它会得到name属性“hoverimage1”
- 然后消失在ID为“hoverimage1”的元素通过基本上执行$('#hoverimage1“)。fadeIn(500);
但问题是name属性没有”#“,我不想写”name =“#hoverimage1 “因为这对身份证来说很混乱。现在我的函数执行$('hoverimage1“)。fadeIn(500);这是不正确的语法。
有人可以帮助我吗?是否可以附加一个”#“到”$(this。 ?的getAttribute())”什么
答
如果要在前面加上一个#
,那么你可以在连接字符串:
$('#' + this.name)
但如果可能的话我会使用的元素索引对于这一点,:
$('.image').mouseenter(function() {
$('.other_images').eq($(this).index()).stop().fadeIn(500);
}).mouseout(function() {
$('.other_images').eq($(this).index()).stop().fadeOut(500);
});
这样,您甚至不需要在父图像的name
属性中编写其他图像的id
。
答
由于该属性为hoverimage1
,因此该脚本正在寻找<hoverimage1>
元素。您需要将#
连接到开头:$("#"+this.getAttribute("name"))
+1不浪费时间创建jQuery对象来获取属性。 – 2013-03-26 22:59:52