如何在列表视图中动态地jquery#tags并设置div id

时间:2013-11-15 23:05:31

标签: c# jquery asp.net listview html-injections

Hello Everyone我想动态地动态设置jquery id和listview div id 我已经通过互联网查看了任何好的例子。

    <script>
        $(function () {
    // I need to set the #accLstViewInner to #accLstViewInner + itemID
            $("#accLstViewInner").accordion({
                collapsible: true, active: false
            });
        });
    </script>

并设置

     <asp:ListView ID="lstAccordionViewInner" Runat="server" >
        <LayoutTemplate>
            // set the div below to #accLstViewInner + itemID as well
            <div id="accLstViewInner">

与资源或想法的任何良好联系?

由于

1 个答案:

答案 0 :(得分:0)

在你提到的代码中没有动态的东西。通常的做法是使用两个列表视图(或转发器)来生成代码或直接在选择器或js变量中输出对象的结果。

我假设您使用类似

之类的代码隐藏来提供
lstAccordionViewInner.DataSource = someListObject;
lstAccordionViewInner.DataBind();

作为一个例子

class someList
{
    public int Id { get; set; }
    public string Name { get; set; }
}

// and an example instance, should be put in a property if you want to access it from your aspx-code
var someListObject = new List<someList>()
{
    new someList() {Id = 1, Name = "#accLstViewInner"},
    new someList() {Id = 2, Name = "#accLstViewInner"},
    new someList() {Id = 3, Name = "#accLstViewInner"},
    new someList() {Id = 4, Name = "#accLstViewInner"},
    new someList() {Id = 5, Name = "#accLstViewInner"}
};

string jqueryResult = someListObject.Aggregate(string.Empty, (current, item) => current + string.Concat(item.Name, "_", item.Id, item == someListObject.Last() ? string.Empty : ", "));
// #accLstViewInner_1, #accLstViewInner_2, #accLstViewInner_3, #accLstViewInner_4, #accLstViewInner_5

此结果可以直接在jQuery选择器中使用

$('<%=someListObject.Aggregate(string.Empty, (current, item) => current + string.Concat(item.Name, "_", item.Id, item == someListObject.Last() ? string.Empty : ", "));%>').accordion({
    collapsible: true, active: false
});

当呈现页面时,这将变为

$('#accLstViewInner_1, #accLstViewInner_2, #accLstViewInner_3, #accLstViewInner_4, #accLstViewInner_5').accordion({
    collapsible: true, active: false
});

但是,既然你有这种模式,我会说除了你想要极端控制之外,做那么多工作只是为了建立一个选择器是愚蠢的。请改用通配符

$("[id^=accLstViewInner]").accordion({
    collapsible: true, active: false
});

处理列表视图...

 <asp:ListView ID="lstAccordionViewInner" Runat="server" >
    <LayoutTemplate>
        // set the div below to #accLstViewInner + itemID as well
        <div id='accLstViewInner_<%#Eval("Id") %>' />'>
        // or possibly
        <div id='accLstViewInner_<%#DataBinder.Eval(Container.DataItem, "Id")%>' />'>
        // ...
        <div id='accLstViewInner_<% DataBinder.Eval(Container.DataItem("Id"))%>' />'>