![](/img/trans.png)
[英]Javascript: Validating dynamically created radio button list control in ASP.NET
[英]using javascript for changing dynamically created ASP.NET image control
我在我的ASP.NET(C#,VS2010)Web應用程序中創建了一個表,其行和單元格應該是動態創建的(從DB讀取),我在每行中都有一個動態創建的圖像(在代碼隱藏文件中),如何用鼠標改變其圖像(顯示懸停)? 使用一個小的JavaScript函數很容易為靜態創建的控件,但如何為動態創建的控件做到這一點? 我可以使用內聯JS函數嗎? 我該如何實施呢?
謝謝
使用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);
這將渲染每個圖像,如下所示:
<img src="image.jpg" class="change-on-hover"
data-alternative-image="image-over.jpg" />
然后在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");
});
data-alternative-image
屬性是一種很好的方法,可以從后面的代碼中將一些信息存儲在圖像標記內,然后您可以在JavaScript事件處理程序中讀取這些信息。 您可以按照自己喜歡的方式創建自己的數據屬性。
有關data-attribute的更多信息: http : //ejohn.org/blog/html-5-data-attributes/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.