画像を差し替えたい
HTML:
<a href="#"><img src="products.jpg" alt="products" /></a>
<a href="#"><img src="another-image.jpg" alt="another-image" /></a>
画像ソースを変更する前に、jQuery 関数.data()を使用して保存します。次に、それらをクリックすると、src プロパティが復元されます。このようなもの:
if ( $(window).width() <= 480 ) {
$('img').each(function (i, k) {
$(k).data('src', $(k).attr('src'));
$(k).attr('src', 'temp_image.jpg');
});
$('img').click(function () {
$(this).attr('src', $(this).data('src'));
});
}
簡単なはずです。
まず、 .click() は、オブジェクトが呼び出されたイベント click に関数をバインドします。.each() 内でイベントをバインドすることはできません (できますが、期待どおりには機能しません)。
次のようなことを試してください:
<div id="banner">
<a href="#"><img src="banner.jpg" id="realImg1" alt="banner" /></a>
<a href="#"><img src="another-image.jpg" id="realImg2" alt="another-image" /></a>
</div>
<script>
$(document).ready(function() {
var counter = 0;
var toggle_images = function () {
if (counter % 2) // if pair, change all pics to "dummy.jpg"
{
$('img').each(function
({
$(this).attr('src', 'dummy.jpg');
};
}
else // if odd restore its initial src (you can recycle the value in alt)
{
$('img').each
({
// get the name from the alt property and append '.jpg'
var pic_path = $(this).attr('alt') + '.jpg'
$(this).attr('src', pic_path);
});
}
counter += 1;
};
$('img').click(toggle_images); // bind the event
</script>