Javascript替换扩展onclick

时间:2014-01-13 19:47:08

标签: javascript jquery

我有一个网站,我有GIF。 Gifs被静态图像取代,点击它们后,它们将替换为gif版本。但是,如果用户第二次点击它们,我想再次更改为静态版本。到目前为止我得到了这个:

问题是,我不能将originExt保持为png例如。如果我第二次点击它,originExt将变为.gif,因此它会将gif更改为gif。我想知道如何在第一次点击该变量后保留.png谢谢

 $(function(){
     $('.gif').click(function(){
           var src = $(this).attr('src');
            var originExt = "."+src.substr(src.lastIndexOf('.') + 1);

            if($(this).hasClass('play'))
            {
                $(this).attr("src", src.replace(/\.gif/i, originExt));
                $(this).removeClass('play');
            }   else
            {
                $(this).attr('src', 'sources/uploads/t/234.gif');
                $(this).addClass('play');
            }
          });
         });

2 个答案:

答案 0 :(得分:0)

将原始扩展名存储在属性中,并在需要时检索:

$(function(){
     $('.gif').click(function(){
           var src = $(this).attr('src');

            if($(this).hasClass('play'))
            {
                // Here you retrieve the original extension from the element's property
                $(this).attr("src", src.replace(/\.gif/i, $(this).prop('origExt')));
                $(this).removeClass('play');
            }   else
            {
                // Here you get the original extension,and save it to a property of the element
                var originExt = "."+src.substr(src.lastIndexOf('.') + 1);   
                $(this).prop('origExt', originExt);
                $(this).attr('src', 'sources/uploads/t/234.gif');
                $(this).addClass('play');
            }
          });
         });

答案 1 :(得分:0)

这是一个选项:

$(function () {
    $('.gif').click(function () {
        var src = $(this).attr('src');
        if (!$(this).attr('data-src')) $(this).attr('data-src', "." + src.substr(src.lastIndexOf('.') + 1));

        if ($(this).hasClass('play')) {
            $(this).attr("src", src.replace(/\.gif/i, $(this).attr('data-src')));
            $(this).removeClass('play');
        } else {
            $(this).attr('src', 'sources/uploads/t/234.gif');
            $(this).addClass('play');
        }
    });
});