admin管理员组

文章数量:1279185

So basicly what I want to make is everytime you click on an image outside of the div "img-container" it changes the src path in "img-container" div. Came this far, now I don't know how to finish this code.

Thanks in advance

<div class="img-container">
  <img id="changeMe" src="">
</div>

<img src="images/preview-1.jpg">
<img src="images/preview-2.jpg">
<img src="images/preview-2.jpg">

$('img').click(function(event) {
   alert($(this).attr('src'));
});

So basicly what I want to make is everytime you click on an image outside of the div "img-container" it changes the src path in "img-container" div. Came this far, now I don't know how to finish this code.

Thanks in advance

<div class="img-container">
  <img id="changeMe" src="">
</div>

<img src="images/preview-1.jpg">
<img src="images/preview-2.jpg">
<img src="images/preview-2.jpg">

$('img').click(function(event) {
   alert($(this).attr('src'));
});
Share Improve this question asked Oct 15, 2014 at 7:51 DarkoDarko 811 silver badge8 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 8

Give them a class

<div class="img-container">
  <img id="changeMe" src="">
</div>

<img class="preview" src="images/preview-1.jpg">
<img class="preview" src="images/preview-2.jpg">
<img class="preview" src="images/preview-2.jpg">

Then do

$('.preview').on('click',  function() {
    $('#changeMe').prop('src', this.src);
});

no need to change the markup just change script as follow

$('img:not(div img)').click(function(event) {
  $(".img-container img").attr('src',$(this).attr('src'));
});

Adneneos' answer is the most efficient.

However, this method would be good if, for some reason, you can't add classes to the images. This uses the .each() method...

$(document).ready(function() {
 $("img[id!='changeMe']").each(function() {
  $(this).click(function() {
   $("#changeMe").attr('src', this.src);
  });
 });
});

Fiddle here

EDIT: You would need to define a more specific of sorts, because this method would check every image on the page. This answer is based on the code provided. However, adeneos answer may be easier.

本文标签: javascriptjQuery how to change img src path onclickStack Overflow