如何改变图像源基于它的类在jQuery中,页面加载后
How to change image source based on its class in jQuery, after the page has loaded
我正在用jQuery构建一个图像滑块,以增强我对该语言的了解。为了指示应该显示图像,我向该<img>
标记添加了一个"selected"类。此外,为了指示导航按钮应该打开/关闭,我在各自的li
中添加了active/inactive类。
例子:
$(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
。它确实正确地将类从active
更改为inactive
,但img src
从未更改。为什么会这样呢?
编辑:
链接到我正在谈论的演示:demo
您必须将更改图像的代码放入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');
});
相关文章:
- Ajax请求文档就绪会导致jquery加载缓慢
- jQuery加载的async和ready函数不工作
- jQuery加载完成事件不起作用
- jQuery加载方法字符集
- 使用jQuery加载页面上的配色方案
- 向使用jQuery加载DOM后添加的字段添加不受限制的文本输入DatePickers
- 我的jQuery加载请求是否被调用了两次
- jquery加载后会触发任何事件吗
- Jquery加载页面时的颜色更改效果
- 在AJAX jQuery加载()之后运行jQuery代码
- 使用jQuery加载页面时自动向上滚动
- 使用 jQuery 加载一系列图像
- 在 Wordpress 中调试 jquery 加载问题
- 使用 jQuery 加载 JSON,然后将其显示给查看器
- Jquery 加载的图像对类没有反应
- jquery加载时间和里面的css样式
- Rails:使用jQuery加载分部
- jQuery加载函数后,jQuery UI自动完成功能不起作用
- jQuery加载窗口,同时等待长函数完成
- "数据表”;jquery加载后CSS样式消失