2
我想用html5數據屬性更改圖像源。我已經嘗試了很多方法,但仍然無法解決,因爲這裏演示的是代碼;jQuery使用html5數據屬性更改圖像源
HTML標記:
<img src="http://placehold.it/300x250&text=Default%20Image" data-imgSmall="http://placehold.it/300x250&text=Small%20Image" data-imgMedium="http://placehold.it/300x250&text=Medium%20Image" data-imgLarge="http://placehold.it/300x250&text=Large%20Image" />
<button class="small">Small Image</button>
<button class="medium">Medium Image</button>
<button class="large">Large Image</button>
jQuery代碼:
var ImgSmall = $('img').data('imgSmall'),
ImgMedium = $('img').data('imgMedium'),
ImgLarge = $('img').data('imgLarge'),
img = $('img');
$('button').click(function() {
if ($(this).hasClass("small")) {
img.attr('src', ImgSmall);
alert(ImgSmall);
}
if ($(this).hasClass("medium")) {
img.attr('src', ImgMedium);
alert(ImgMedium);
}
if ($(this).hasClass("large")) {
img.attr('src', ImgLarge);
alert(ImgLarge);
}
});
但這代碼仍然沒有工作,PLZ建議在那裏我錯了,在此先感謝:)
http://jsfiddle.net/pSs7v/,工作示例這裏 –
爲什麼在你調用三次之前不緩存'img'? – crush