[英]How to change image source based on its class in jQuery, after the page has loaded
I'm building an image slider in jQuery to bolster my knowledge of the language. 我正在jQuery中构建图像滑块,以增强我对该语言的了解。 In order to indicate that an image should be shown, I add a "selected" class to that
<img>
tag. 为了指示应该显示图像,我向该
<img>
标签添加了一个“ selected”类。 Additionally, in order to indicate that a nav button should be toggled on/off, I add an active / inactive class to that respective li
. 另外,为了指示应打开/关闭导航按钮,我向相应的
li
添加了一个活动 / 非活动类。
Example here: 这里的例子:
$(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');
}
});
FYI The HTML that I'm working on looks like this: 仅供参考 ,我正在处理的HTML如下所示:
Navigation buttons: 导航按钮:
<ul id="navigation">
<li><img class="inactive" id="1" src="images/button2.png"></li>
Images in slider 滑块中的图像
<img src="images/slider1.jpg" id="image-1" class="slider selected">
The problem: 问题:
Whenever I click a new navigation button and remove the active
class from the nav buttons and add the inactive
class, it should also change the source of the image from button1.png
to button2.png
. 每当我单击一个新的导航按钮并从导航按钮中删除
active
类并添加inactive
类时,它也应将图像源从button1.png
为button2.png
。 It does change classes from active
to inactive
properly, but the img src
never changes. 确实确实将类从
active
更改inactive
,但是img src
从未更改。 Why is this the case? 为什么会这样呢?
Edit: Link to a demo of what I'm talking about: demo 编辑:链接到我正在谈论的演示 : 演示
You have to put the code to change the image inside the click
function, otherwise it will be executed only one time: when the page loads. 您必须将代码更改为在
click
函数中更改图像,否则它将仅执行一次:页面加载时。 And obviously your image will never change anymore. 很显然,您的形象将永远不会改变。
Here's the code: 这是代码:
$(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');
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.