jQuery find('img').attr('src')不起作用

use*_*851 0 jquery

以下代码不起作用:

find('img').attr('src')

我希望将鼠标悬停在旁边区域并打开/关闭图像更改.

HTML

<aside style="width:200px;height:300px;text-align:center;">
  <img class="img" src="imgs/photo_off.png" alt="" >
</aside>
Run Code Online (Sandbox Code Playgroud)

JavaScript的

$("aside").hover(
    function () {
        $(this).find('img').attr('src') = $(this).find('img').attr('src').replace("_off", "_on");
    },
    function () {
        $(this).find('img').attr('src') = $(this).find('img').attr('src').replace("_on", "_off");
    }
);
Run Code Online (Sandbox Code Playgroud)

Aru*_*hny 5

您不能像这样为函数调用语句赋值.它应该抛出一个错误

未捕获的ReferenceError:赋值中的左侧无效

使用.attr的setter版本(名称,值)

$(this).find('img').attr('src', $(this).find('img').attr('src').replace("_off", "_on"));
Run Code Online (Sandbox Code Playgroud)

或.attr(名称,回调)

$("aside").hover(function () {
    $(this).find('img').attr('src', function (i, src) {
        return src.replace("_off", "_on");
    })
}, function () {
    $(this).find('img').attr('src', function (i, src) {
        return src.replace("_on", "_off");
    })
});
Run Code Online (Sandbox Code Playgroud)