简体   繁体   中英

image not getting displayed after changing src attribute of img using jquery

I have an image on my page. On clicking a button I want to change the src of the image and display the new image. Below is my code.

<img id="img_change" src = "~/content/images/img1.jpg" />

Below i have

<script>
$("document").ready(function() {
  $("button").click(function() {
    $("#img_change").attr("src","~/content/images/img2.jpg");
  });
});

On clicking the image is not getting displayed. I've tried all that I know.

It's because your selector is not correct. Your code should be like this:

$("document").ready(function() {
  $("button").click(function() {
    // "#img_change" and not "img_change"
    $("#img_change").attr("src","~/content/images/img2.jpg");
  });
});

You need to have # in front of your selector since you are using an ID to target the correct element.

@Swatto Thnku so much. The browser console error was indicating that the path was not accessible. I changed it to $("#img_change").attr("src","/Content/Images/img2.jpg"); and it is working now. Thnks again

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM