2011-11-28 101 views
0

我想更改下面用于将图像更改为链接/图像的按钮。任何帮助,将不胜感激!谢谢。JavaScript交换/更改点击图片

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<style> 
</style> 

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script> 
<script type='text/javascript'> 
onload = function() { 
    var buttonData = [ 
     {src:'fareast.gif', href:'http://google.com'}, 
     {src:'middlearth.jpg', href:'http://yahoo.com'}, 
     {src:'europe.jpg',  href:'http://chappo.cc'} 
    ]; 
    var $im1 = $("[name='im1']").click(function(){ window.open($(this).attr('href')); }); 
    $(".imgSwap").each(function(i) { 
     var $b = $(this), d = buttonData[i] || buttonData[buttonData.length-1]; 
     $b.click(function() { $im1.attr({src:d.src,title:$(this).html(),href:d.href}); }); 
     if(i==0) { $b.click(); } 
    }); 
}; 
</script> 
</head> 

<body> 

<img name="im1" height="300" width="300" /><br/> 
<button class="imgSwap">Far East</button> 
<button class="imgSwap">Middle Earth</button> 
<button class="imgSwap">Europe</button> 
</body> 
</html> 

请帮忙!

+1

如果我理解你正确地只是改变了' lfxgroove

+0

你的代码工程:http://jsfiddle.net/kbEJp/ –

回答

2

首先,HTML:

<a href="#" class="imgSwap"><img src="path/to/image/far_east_button.gif" class="buttonImage" /></a> 
<a href="#" class="imgSwap"><img src="path/to/image/middle_earth.gif" class="buttonImage" /></a> 
<a href="#" class="imgSwap"><img src="path/to/image/europe.gif" class="buttonImage" /></a> 

然后,buttonData:

var buttonData = [ 
    //titles added 
    {src:'fareast.gif', href:'http://google.com', title:'Far East'}, 
    {src:'middlearth.jpg', href:'http://yahoo.com', title:'Middle Earth'}, 
    {src:'europe.jpg',  href:'http://chappo.cc', title:'Europe'} 
]; 

然后,单击处理:

$(".imgSwap").each(function(i) { 
var $b = $(this), d = buttonData[i] || buttonData[buttonData.length-1]; 
$b.click(function() { 
    $im1.attr({src:d.src, title:d.title, href:d.href});//note change to composition of title 
    return false;//Added to suppresses default hyperlink action of <a> links. 
}).attr('title', d.title); 
if(i==0) { $b.click(); } 
}); 

希望这将解决这个问题。

+1

你的JavaScript的实力让我嫉妒 – phpmeh

+1

@phpmeh我只是一个学习者。我敢打赌你更好:-) –

2

做这个

<script> 
function changeImg(val) 
{ 
    if(val == 1) 
{ 
document.getElementById('im1').src = "fareast.gif"; 
} 
if(val == 2) 
{ document.getElementById('im1').src = "middlearth.jpg";} 
if(val == 3) 
{ document.getElementById('im1').src = "europe.jpg";} 
} 

</script> 

<img name="im1" id='im1' height="300" width="300" /><br/> 
<button class="imgSwap" onclick="changeImg('1');">Far East</button> 
<button class="imgSwap" onclick="changeImg('2');">Middle Earth</button> 
<button class="imgSwap" onclick="{changeImg('3');">Europe</button>