私は動的に値を割り当てる自分のページで<asp:CheckBoxList>
使用しています。RepeatLayout="Flow"
ページが最初に読み込まれた場合 ( !IsPostBack
)、レンダリングされたバージョンは次のようになります。
<span children="Cat">
<input id="ctl00_Menu_Category_0" type="checkbox" name="ctl00$Menu$Category$0"/>
<label for="ctl00_Menu_Category_0">Cat</label>
</span>
<br/>
<span class="Cat">
<input id="ctl00_Menu_Category_1" type="checkbox" name="ctl00$Menu$Category$1"/>
<label for="ctl00_Menu_Category_1"> - SubCat1</label>
</span>
children
は jQuery コードに使用する属性であるため、ユーザーが をチェックするCat
と、すべてSubCat
の もチェックされます。
jQuery コードは、 -attribute<span>
と等しいクラスを持つすべての を検索するため、jQuery が機能するこの構造を維持する必要があります。children
しかし、ページをリロードしたり、リンクをたどったりすると、リストは突然次のようになります。
<input id="ctl00_Menu_Category_0" type="checkbox" name="ctl00$Menu$Category$0"/>
<label for="ctl00_Menu_Category_0">Cat</label>
<br/>
<input id="ctl00_Menu_Category_1" type="checkbox" name="ctl00$Menu$Category$1"/>
<label for="ctl00_Menu_Category_1"> - SubCat1</label>
それはどのように可能ですか?値を一度だけリストに割り当てたのに、PostBack 後に再レンダリングされるのはなぜですか? また、それを防ぐにはどうすればよいですか?
編集
リストを作成するコードは次のとおりです。
// Get all available categories that are not a child of another category
DataTable categoryParents = functions.SelectSql(Resources.Data.GetCategoryParents);
// Get the child categories
foreach (DataRow parent in categoryParents.Rows)
{
// Add the category
ListItem parentItem = new ListItem(parent["Name"].ToString(), parent["Name"].ToString());
parentItem.Attributes.Add("children", parent["Name"].ToString().Replace(' ', '_'));
Category.Items.Add(parentItem);
// For every parent category, get all its child categories
DataTable categoryChildren = functions.SelectSql(Resources.Data.GetCategoryChildrenByParent.Replace("##PARENTID##", parent["ID"].ToString()));
// Add the child categories after their parents
foreach (DataRow child in categoryChildren.Rows)
{
ListItem item = new ListItem(" - " + child["Name"].ToString(), parent["Name"].ToString() + "\\" + child["Name"].ToString());
item.Attributes.Add("class", parent["Name"].ToString().Replace(' ', '_'));
Category.Items.Add(item);
}
}
Category.DataBind();
jQuery 自体は HTML に対して何もしません。親がチェックされたときに子カテゴリをチェックする機能を保持するだけです。
$("#Category :checkbox").click(function(){
var checked = $(this).attr("checked");
var children = $(this).parent("span").attr("children");
$("#Category ." + children + " :checkbox").attr("checked", checked);
});