2014-01-28 51 views
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建议在那里我错了,在此先感谢:)

+0

http://jsfiddle.net/pSs7v/,工作示例这里 –

+2

为什么在你调用三次之前不缓存'img'? – crush

回答

7

the HTML5 spec

所有的HTML元素属性名在HTML文件中得到 ASCII-小写自动

使用小写名称:

var ImgSmall = $('img').data('imgsmall'), 
    ImgMedium = $('img').data('imgmedium'), 
    ImgLarge = $('img').data('imglarge'), 
    img = $('img'); 
+0

谢谢:),它的工作原理 –