简体   繁体   English

使用javascript更改动态创建的ASP.NET图像控件

[英]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? 我在我的ASP.NET(C#,VS2010)Web应用程序中创建了一个表,其行和单元格应该是动态创建的(从DB读取),我在每行中都有一个动态创建的图像(在代码隐藏文件中),如何用鼠标改变其图像(显示悬停)? it is easy using a small JavaScript function for statically created controls, but how can it be done for dynamically created controls? 使用一个小的JavaScript函数很容易为静态创建的控件,但如何为动态创建的控件做到这一点? can I use inline JS functions? 我可以使用内联JS函数吗? how should I implement it? 我该如何实施呢?

thanks 谢谢

Give the images you create dynamically a class, using their CssClass property: 使用CssClass属性动态地为您创建的图像提供一个类:

// 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: 然后在jQuery中,您可以找到使用此类绑定行为的所有图像:

$("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. data-alternative-image属性是一种很好的方法,可以从后面的代码中将一些信息存储在图像标记内,然后您可以在JavaScript事件处理程序中读取这些信息。 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/ 有关data-attribute的更多信息: http//ejohn.org/blog/html-5-data-attributes/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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