简体   繁体   中英

using javascript for changing dynamically created ASP.NET image control

I've created a table in my ASP.NET (C#,VS2010) web app whose rows and cells should be created dynamically (read from DB), I have an image in each row which is being created dynamically (in codebehind file), how can I change its image (display a hover) with mouse over? it is easy using a small JavaScript function for statically created controls, but how can it be done for dynamically created controls? can I use inline JS functions? how should I implement it?

thanks

Give the images you create dynamically a class, using their CssClass property:

// Dynamically create the image control in code behind
Image image = new Image();
Image.CssClass = "change-on-hover";
Image.ImageUrl = "image.jpg"; // Of course, this is dynamic from the database

// Save the alternative image URL in a data-attribute
Image.Attributes["data-alternate-image"] = "image-over.jpg";

parent.Controls.Add(image);

This will render each image like this:

<img src="image.jpg" class="change-on-hover" 
  data-alternative-image="image-over.jpg" />

Then in jQuery, you can find all the images with this class to bind the behavior:

$("img.change-on-hover")
  .on("mouseover", function(e) {
    // Save original src (image.jpg)
    $(this).data("original-image") = this.src;

    // Change src to alternative (image-over.jpg)
    this.src = $(this).data("data-alternate-image");
  })
  .on("mouseout", function(e) {
    // Change src back to original
    this.src = $(this).data("original-image");
  });

The data-alternative-image attribute is a nice way to store some information inside the image tag from code behind, that you can then later read in your JavaScript event handler. You can make your own data-attributes any way you like.

Some more info about the data-attribute: http://ejohn.org/blog/html-5-data-attributes/

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