2

我无法获取 attr 函数来更改类并将其保留到下一次单击。它也不会使用新的 mouseenter 和 mouseout 函数。任何想法我做错了什么?

HTML

<a href="" id="play" class="pause"><div id="playctrl"><img id="pausectrl" class="play" src="images/play1.png" ></div></a>

查询

$('.pause').click(function(){
    $('#pausectrl').attr({
        src: 'images/pause1.png',
        class: 'paused' 
    });

    return false;
});

$('.play').mouseenter(function(){
    $(this).attr('src','images/play2.png');
}).mouseout(function(){
    $(this).attr('src','images/play1.png');
});

$('.paused').mouseenter(function(){
    $(this).attr('src','images/pause2.png');
}).mouseout(function(){
    $(this).attr('src','images/pause1.png');
});

这是该页面示例的链接。MMA 幻灯片控件示例

4

4 回答 4

4

您正在设置src链接。你想这样做:

$(this).find('img').attr('src', 'myimage.png');
于 2011-05-12T17:16:02.327 回答
2

当你说:

它也不会使用新的 mouseenter 和 mouseout 函数

我猜这是因为当你的代码运行时,你的对象还没有类,所以它们没有绑定到事件处理程序。您可以使用 live 函数正确绑定您的事件。

$('.pause').click(function(){
    $('#pausectrl').attr({
        src: 'images/pause1.png',
        class: 'paused' 
    });
  return false;
});

$('.play').live("mouseenter", function() {
  $(this).attr('src','images/play2.png');
});

$('.play').live("mouseout", function(){
  $(this).attr('src','images/play1.png');
});

$('.paused').live("mousenter", function() {
  $(this).attr('src','images/pause2.png');
});


$('.paused').live("mouseout", function(){
  $(this).attr('src','images/pause1.png');
});
于 2011-05-12T17:22:52.333 回答
1

对于第二部分:

$('.paused').mouseenter(function(){
  $(this).attr('src','images/pause2.png');
  }).mouseout(function(){
  $(this).attr('src','images/pause1.png');
});

您最好使用 jQuery 设置类名并使用 CSS 和图像精灵进行图像替换。

就像是:

.paused {background: url(/images/paused.png) 0 0 no-repeat;}
.paused:hover {background-position: 0 15px;} /* Or whatever the position in the sprite */
于 2011-05-12T17:25:13.583 回答
1

您将 src 设置在错误的标签上,请改用以下代码:

$("img.play", $(this)).attr('src', 'thenewimage.png');

'$(this)' 部分是 jQuery 尝试查找具有类 'play' 的图像的起始位置。在我看来,这是一个有效的解决方案..

完整的js代码:

$('.play').mouseenter(function(){
  $("img.play", $(this)).attr('src','images/play2.png');
  }).mouseout(function(){
  $("img.play", $(this)).attr('src','images/play1.png');
  });

HTML保持不变..

$('.paused').mouseenter(function(){
  $("img.play", $(this)).attr('src','images/pause2.png');
  }).mouseout(function(){
  $("img.play", $(this)).attr('src','images/pause1.png');
  });

`

于 2011-05-12T17:17:49.907 回答