javascript change image, href onclick = looking for simpliest method
What is the simpliest method to change image src, when I click on a href -with JQuery?
img id="my_image" class="icon" src="1.png" alt="1.png" border="0" />
< a href="#" id="1">
< a href="#" id="2">
< a h开发者_StackOverflow社区ref="#" id="3">
1.png, 2.png, 3.png
Href is OK with # or would be better to placce here some JS?
You should .bind()
help a .click()
help event listener on your anchors. In that listener, you change the src attribute by invoking .attr()
help
$('a').click(function(event) {
$('#my_image').attr('src', function(i, src) {
return event.target.id + '.png';
});
return false;
});
<img id="my_image" class="icon" src="1.png" alt="1.png" border="0" />
<a onclick="changeImage(this)" href="#" id="1">1</a>
<a onclick="changeImage(this)" href="#" id="2">2</a>
<a onclick="changeImage(this)" href="#" id="3">3</a>
<script>
function changeImage(thisDiv){
document.getElementById('my_image').src = thisDiv.id+".png"
}
</script>
Edit: Didn't see the jQuery requirement!
This ought to work:
<a href="javascript:$('#my_image').attr('src', '2.png');" id="1">
$('a').click(function(e) {
var id = this.id;
$('#my_image').attr('src', id + '.png');
e.preventDefault();
});
精彩评论