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