代码之家  ›  专栏  ›  技术社区  ›  tomtom

加载页面后,如何根据jQuery中的类更改图像源

  •  1
  • tomtom  · 技术社区  · 10 年前

    我正在jQuery中构建一个图像滑块,以增强我的语言知识。为了指示应该显示图像,我向其中添加了一个“selected”类 <img> 标签此外,为了指示导航按钮应该打开/关闭,我添加了一个 忙碌的 / 不活跃的 类到相应的 li .

    此处示例:

    $(document).ready(function(){
        initPics();
        currentImage = $('.selected').attr('id');
    
    
        var navButton = $("li").find("img");
        //show the right image when the nav button is clicked
        $(navButton).on('click',function(){
            $("#"+currentImage).removeClass('selected');
            $("#"+currentImage).addClass('notSelected');
    
            //change nav button when a different one is clicked
            $('#navigation').children('li').children("img").removeClass('active');
            $('#navigation').children('li').children("img").addClass('inactive');
    
        });
    
        if ($("li img").hasClass('active')){
            $(this).find(".active").attr('src','images/button1.png');
        } else {
            $(this).attr('src','images/button2.png');
        }
    
    
    });
    

    供参考 我正在处理的HTML如下所示:

    导航按钮:

    <ul id="navigation">
                <li><img class="inactive" id="1" src="images/button2.png"></li>
    

    滑块中的图像

    <img src="images/slider1.jpg" id="image-1" class="slider selected">
    

    问题是:

    每当我单击新的导航按钮并删除 active 类,并添加 inactive 类,它 应该 也可以更改图像的来源 button1.png button2.png 。它确实将类从 忙碌的 不活跃的 正确,但 img src 永远不会改变。为什么会这样?


    编辑: 链接到我正在谈论的内容的演示: demo

    1 回复  |  直到 10 年前
        1
  •  1
  •   Marco Bonelli    10 年前

    您必须将代码放入 click 函数,否则将只执行一次:加载页面时。显然你的形象永远不会改变。

    代码如下:

    $(navButton).on('click',function(){
        $("#"+currentImage).removeClass('selected');
        $("#"+currentImage).addClass('notSelected');
    
        //change nav button when a different one is clicked
        $('#navigation').children('li').children("img").removeClass('active');
        $('#navigation').children('li').children("img").addClass('inactive');
    
        // change image
        $("li img.active").attr('src','images/button1.png');
        $("li img.inactive").attr('src','images/button2.png');
    });