[ASP.NET] 動態為 RadioButtonList 加上自訂屬性
情境:
RadioButtonList 按下某一個 RadioButton 後顯示特定屬性
解決方案:
在後端動態的加上自訂的屬性,在前端加上 click 行為
實作:
使用 Attributes 新增 subValue 屬性
{ var subId = item.Value; var subName = item.Text; var subValue = laborSafeties.First(p => p.SubId == subId).SubValue; item.Attributes.Add("subValue", subValue); }
生成的 html 長這樣,如下圖:
我在 pageLoad 為 RadioButtonList 加上 onclick 事件,當我點選 radio 後去讀取剛剛自訂的屬性,自定義的屬性會在 span,它在 input 的上一層,所以要用 $(this).parent() 來抓上一層
$("input[type='radio']").on('click', function(e) { var subValue = $(this).parent().attr("subValue"); if (subValue===undefined) { return; } console.log(subValue); }); }
文章出自:http://www.dotblogs.com.tw/yc421206/archive/2015/09/09/153321.aspx
若有謬誤,煩請告知,新手發帖請多包涵
Microsoft MVP Award 2010~2017 C# 第四季
Microsoft MVP Award 2018~2022 .NET