jQuery : Use an alternative to .toggle() which is deprecated

前端 未结 4 868
一生所求
一生所求 2021-01-13 23:52

I have some images with class name \".mute_btn\" and when i click on them, my images source is changing :

$(\'.mute_btn\').toggle(function () {
        var c         


        
4条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-14 00:39

    I suspect the problem is that you have multiple images, but you're trying to manage their clicked status with a single variable. Try storing the clicked status against the individual elements as follows:

    $('.mute_btn').click(function() {
        if ($(this).data("clicked")) {
            var src = $(this).attr("src");
            src = src.replace(/(.*)-over\.(png|gif|jpg|jpeg)$/, "$1.$2");
            $(this).attr("src", src);
            $(this).data("clicked",false);
        }
        else {
            var src = $(this).attr("src");
            src = src.replace(/(.*)\.(png|gif|jpg|jpeg)$/, "$1-over.$2");
            $(this).attr("src", src);
            $(this).data("clicked",true);
        }
    });
    

    Note that you could cache your $(this) object instead of making a new one each time, but I've not done so so that the change needed to solve your problem is more obvious.

提交回复
热议问题