[英]How to change image source based on its class in jQuery, after the page has loaded
我正在jQuery中構建圖像滑塊,以增強我對該語言的了解。 為了指示應該顯示圖像,我向該<img>
標簽添加了一個“ selected”類。 另外,為了指示應打開/關閉導航按鈕,我向相應的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
。 確實確實將類從active
更改inactive
,但是img src
從未更改。 為什么會這樣呢?
您必須將代碼更改為在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');
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.