jquery - 翻转时更改 IMG src
我有以下代码:(这里有小提琴)
<img class="changeable" src="http://placehold.it/100x120&text=anniversary">
<ul class="rollover_list">
<li><a href="#" rel="http://placehold.it/100x120&text=anniversary"><span class="orange">> </span>Anniversary</a></li>
<li><a href="#" rel="http://placehold.it/100x120&text=birthday"><span class="orange">> </span>Birthday</a></li>
<li><a href="#" rel="http://placehold.it/100x120&text=christmas"><span class="orange">> </span>Christmas</a></li>
<li><a href="#" rel="http://placehold.it/100x120&text=wedding"><span class="orange">> </span>Wedding</a></li>
</ul>
,我正在尝试更改 src基于锚点的rel值的图像属性。
我正在尝试这个 jquery -
$("ul.rollover_list li a").hover(function() {
var $link = $(this).attr('rel');
var $target = $(this).closest('img.changeable');
$($target).attr('src', $link);
});
因为我需要在页面上多次使用它。
我是否正确地认为 .closest() 将通过遍历 DOM 来找到最近的匹配元素?
不知道我错过了什么,但并不快乐。
I've the following code: (a fiddle is here)
<img class="changeable" src="http://placehold.it/100x120&text=anniversary">
<ul class="rollover_list">
<li><a href="#" rel="http://placehold.it/100x120&text=anniversary"><span class="orange">> </span>Anniversary</a></li>
<li><a href="#" rel="http://placehold.it/100x120&text=birthday"><span class="orange">> </span>Birthday</a></li>
<li><a href="#" rel="http://placehold.it/100x120&text=christmas"><span class="orange">> </span>Christmas</a></li>
<li><a href="#" rel="http://placehold.it/100x120&text=wedding"><span class="orange">> </span>Wedding</a></li>
</ul>
and I'm attempting to change the src attribute of the image based on the rel value of the anchor.
I'm trying this jquery -
$("ul.rollover_list li a").hover(function() {
var $link = $(this).attr('rel');
var $target = $(this).closest('img.changeable');
$($target).attr('src', $link);
});
as I need to use it multiple times on a page.
Am I right in thinking that .closest() will locate the nearest matching element by traversing up the DOM?
Don't know what I'm missing but it ain't happy.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
显示为...的那条线
可能应该是...
That line that appears as...
should probably be...
你的 jQuery 有两个问题:
closest()
方法只能在树中工作,换句话说:只有当想要的结果是当前元素的父元素时它才会工作。$($target)
。$target
已经是一个元素,您无法使用元素作为选择器来选择元素,因为您需要像find
这样的方法,但是,这不是'不是你想要做的。http://jsfiddle.net/U7SNz/2/
You have 2 problems in your jQuery:
closest()
method only works in trees, in other words: it will only work if the wanted result is a parent of the current element.$($target)
.$target
is already an element, you can't select an element using an element as a selector, for that you'd need a method likefind
however, this isn't what you were trying to do.http://jsfiddle.net/U7SNz/2/