根据JSON信息定位HTML div

时间:2014-12-29 15:36:34

标签: javascript jquery html asp.net json

我正在创建一个仪表板,我可以使用jQuery,JSON和通用处理程序将信息保存到我的数据库。现在,我能够使用WebService和JSON回调我的数据库信息。我的数据库信息如下所示..

enter image description here

在准备好文档时,我使用它来从JSON

中检索表中的信息
$.ajax({
    type: "Post",
    contentType: "application/json; charset=utf-8",
    url: "Webservices/RetrieveWidgets.asmx/GetWidgets",
    dataType: "json",
    success: function (response) {
        var te = response;
        function sortResults(prop, asc) {
            te.d = te.d.sort(function (a, b) {
                if (asc) return (a[prop] > b[prop]) ? 1 : ((a[prop] < b[prop]) ? -1 : 0);
                else return (b[prop] > a[prop]) ? 1 : ((b[prop] < a[prop]) ? -1 : 0);
            });
         }

         sortResults('SortNo', true);

         for (var i = 0; i < te.d.length; i++) {
             $('#test ul').append('<li>' + te.d[i].Title + '</li>');
             console.log(te.d[i])
         }
      },
      error: function (repo) {
           console.log(repo);
           $("#console").html('<div class="fail">Dashboard could no load!</div>').css('visibility', 'visible').fadeTo(600, 1);
           setTimeout(function () {
              $('#console').delay(500).fadeTo(600, 0);
          }, 1000);
      }
});

我得到了上述帮助...出于测试目的,这已被添加到HTML

<div id="test">
       <ul>

       </ul>
</div>

这就是显示的内容。

enter image description here

所以发生了什么,它由SortNo排序并显示小部件的标题。前3个在SortNo 0中,依此类推。这确实帮助我传递了JSON。这是我的仪表板的样子..

enter image description here

这就是我的aspx页面的样子(只有一个&#39;列才能得到一个想法)

    <div class="column" id="column1" runat="server">
        <div class="dragbox" id="CurrentDealsWidget" runat="server" visible="false">
            <h2 style="font-size: 14pt">Current Deals per Location</h2>
            <div class="dragbox-content">
                <asp:GridView ID="gvCurrentLocationTotals" runat="server" AutoGenerateColumns="False"
                    DataKeyNames="InternallocationID" BackColor="White" BorderColor="#CCCCCC"
                    BorderStyle="None" BorderWidth="1px" CellPadding="4" ForeColor="Black"
                    GridLines="Horizontal" Width="100%">
                    <Columns>
                        <asp:TemplateField HeaderText="ID" InsertVisible="False" SortExpression="ID" Visible="False">
                            <ItemTemplate>
                                <asp:Label ID="lblID" runat="server" Text='<%# Bind("InternallocationID") %>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Name" SortExpression="Name">
                            <ItemTemplate>
                                <asp:Label ID="lblName" runat="server" Text='<%# Bind("LocationName") %>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Count" ItemStyle-HorizontalAlign="Center">
                            <ItemTemplate>
                                <asp:Label ID="lblCount" runat="server" Text="totes"></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                    <FooterStyle BackColor="#CCCC99" ForeColor="Black" />
                    <HeaderStyle BackColor="#333333" Font-Bold="True" ForeColor="White" />
                    <PagerStyle BackColor="White" ForeColor="Black" HorizontalAlign="Right" />
                    <SelectedRowStyle BackColor="#CC3333" Font-Bold="True" ForeColor="White" />
                    <SortedAscendingCellStyle BackColor="#F7F7F7" />
                    <SortedAscendingHeaderStyle BackColor="#4B4B4B" />
                    <SortedDescendingCellStyle BackColor="#E5E5E5" />
                    <SortedDescendingHeaderStyle BackColor="#242121" />
                </asp:GridView>
            </div>
        </div>
        <div class="dragbox" id="StorePayrollWidget" runat="server" visible="false">
            <h2 style="font-size: 14pt">Store's Payroll</h2>
            <div class="dragbox-content">

                <asp:DropDownList ID="ddlPayrollStores" runat="server" OnSelectedIndexChanged="ddlPayrollStores_SelectedIndexChanged" AutoPostBack="true">
                </asp:DropDownList>
                <asp:UpdatePanel ID="UpdatePanelPayroll" runat="server">
                    <Triggers>
                        <asp:AsyncPostBackTrigger ControlID="ddlPayrollStores" EventName="SelectedIndexChanged"></asp:AsyncPostBackTrigger>
                    </Triggers>
                    <ContentTemplate>
                        <div class="dragbox-content">
                            <asp:Label ID="lblLabelOverTime" runat="server" Text="Total Overtime Hours: " Width="350px"></asp:Label>
                            <asp:Label ID="lblTotalOvertime" runat="server" Text=""></asp:Label>
                            <br />
                            <br />
                            <asp:Label ID="lblLabelHoliday" runat="server" Text="Total Holiday: " Width="350px"></asp:Label>
                            <asp:Label ID="lblTotalHoliday" runat="server" Text=""></asp:Label>
                            <br />
                            <br />
                            <asp:Label ID="lblLabelVacation" runat="server" Text="Total Vacation: " Width="350px"></asp:Label>
                            <asp:Label ID="lblTotalVacation" runat="server" Text=""></asp:Label>
                            <br />
                            <br />
                            <asp:Label ID="lbllableTotalHours" runat="server" Text="Total Hours: " Width="350px"></asp:Label>
                            <asp:Label ID="lblTotalStoreHours" runat="server" Text=""></asp:Label>
                            <br />
                            <br />
                            <asp:Label ID="lblLabelPay" runat="server" Text="Total Pay: " Width="350px"></asp:Label>
                            <asp:Label ID="lblTotalPay" runat="server" Text=""></asp:Label>
                            <br />
                            <br />
                            <div style="align-content: center">
                                <asp:LinkButton ID="lbDetailed" runat="server" Text="Detailed Report" PostBackUrl="~/Reporting/Payroll/StorePayroll.aspx"></asp:LinkButton>
                            </div>
                        </div>
                    </ContentTemplate>
                </asp:UpdatePanel>
            </div>
        </div>
        <div class="dragbox" id="ObjectiveWidget" runat="server" visible="false">
            <h2 style="font-size: 14pt">Store Objectives-<asp:HyperLink ID="hlDaily" runat="server" NavigateUrl="~/Reporting/DailyReports/SalesByModel.aspx">Daily Report</asp:HyperLink></h2>
            <div class="dragbox-content">
                <asp:UpdatePanel ID="upObjective" runat="server">
                    <Triggers>
                        <asp:AsyncPostBackTrigger ControlID="ddlNewUsed" EventName="SelectedIndexChanged" />
                    </Triggers>
                    <ContentTemplate>
                        <div style="width: 100%">
                            <div style="text-align: center">
                                <asp:Label ID="lblObjNotice" runat="server" Text="Notice: If your dealership is in red; monthly objectives need updated!" Font-Bold="true" ForeColor="Red"></asp:Label>
                                &nbsp;<br />
                                <asp:DropDownList ID="ddlObjDealership" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlObjDealership_SelectedIndexChanged" Style="height: 22px">
                                </asp:DropDownList>
                                <asp:DropDownList ID="ddlNewUsed" runat="server" OnSelectedIndexChanged="ddlNewUsed_SelectedIndexChanged" AutoPostBack="true">
                                    <asp:ListItem></asp:ListItem>
                                    <asp:ListItem>New</asp:ListItem>
                                    <asp:ListItem>Used</asp:ListItem>
                                </asp:DropDownList>
                                <asp:DropDownList ID="ddlObjectiveMake" runat="server" Width="155px" OnSelectedIndexChanged="ddlObjectiveMake_SelectedIndexChanged" AutoPostBack="true"></asp:DropDownList>
                            </div>
                            <table style="display: inline-block; width: 45%">
                                <tr>
                                    <td style="width: 100%">
                                        <asp:Label ID="lblCommitObj" runat="server" Text="Commit OBJ: " Width="100%"></asp:Label><asp:TextBox ID="tbCommitObj" runat="server" Width="100%"></asp:TextBox>
                                    </td>
                                </tr>
                                <tr>
                                    <td style="width: 100%">
                                        <asp:Label ID="lblCommitGross" runat="server" Text="Commit Gross OBJECT: " Width="100%"></asp:Label><asp:TextBox ID="tbCommitGross" runat="server" Width="100%"></asp:TextBox>
                                    </td>
                                </tr>
                                <tr>
                                    <td style="width: 100%">
                                        <asp:Button ID="btnSubmitDaily" runat="server" Text="Submit" Height="32px" OnClick="btnSubmitDaily_Click" Width="68px" />
                                    </td>
                                </tr>
                                <tr>
                                    <td style="width: 100%">
                                        <asp:Label ID="lblDailyMess" runat="server"></asp:Label>
                                    </td>
                                </tr>
                            </table>
                            <table style="float: right; width: 45%" title="Current Monthly Objectives">
                                <caption>
                                    <asp:Label ID="lblTitle" runat="server" Font-Bold="true" Font-Size="Small" Text="Current Monthly Objectives"></asp:Label></caption>
                                <tr>
                                    <td style="text-align: center">
                                        <br />
                                        <asp:Label ID="lblObj" runat="server" Font-Bold="true" Text="Obj: "></asp:Label>
                                        <br />
                                        <br />
                                        <br />
                                        <asp:Label ID="lblCurrentObj" runat="server" Text=""></asp:Label>
                                    </td>
                                    <td style="text-align: center">
                                        <br />
                                        <asp:Label ID="lblGross" runat="server" Font-Bold="true" Text="Gross: "></asp:Label>
                                        <br />
                                        <br />
                                        <br />
                                        <asp:Label ID="lblCurrentGross" runat="server" Text=""></asp:Label>
                                    </td>
                                </tr>
                            </table>
                        </div>
                    </ContentTemplate>
                </asp:UpdatePanel>
            </div>
        </div>
    </div>

我使用这个jQuery来拖放小部件..

$(function () {
        $('.dragbox')
        .each(function () {
            $(this).hover(function () {
                $(this).find('h2').addClass('collapse');
            }, function () {
                $(this).find('h2').removeClass('collapse');
            })
            .find('h2').hover(function () {
                $(this).find('.configure').css('visibility', 'visible');
            }, function () {
                $(this).find('.configure').css('visibility', 'hidden');
            })
            .click(function () {
                $(this).siblings('.dragbox-content').toggle();
                updateWidgetData();
            })
            .end()
            .find('.configure').css('visibility', 'hidden');
        });

        $('.column').sortable({
            connectWith: '.column',
            handle: 'h2',
            cursor: 'move',
            placeholder: 'placeholder',
            forcePlaceholderSize: true,
            opacity: 0.4,
            stop: function (event, ui) {
                updateWidgetData();
            }
        })
        .disableSelection();
    });

我的问题是,如何使用与文档准备好的小部件名称相同的ID来定位div?例如,具有id CurrentDealsWidget的div是表中的第一个记录,其中SortNo:0,ColumnId:1,Collapsed:0和UserId:1。这意味着此div需要位于具有id&的div中#34;列1&#34;并在第一个位置。我对jQuery和javascript不是很好,所以我不确定如何解决这个问题。非常感谢任何帮助!

更新:这是我更新小部件信息的方式..

的jQuery

function updateWidgetData() {
        var items = [];
        $('.column').each(function () {
            var columnId = $(this).attr('id');
            $('.dragbox', this).each(function (i) {
                var collapsed = 0;
                if ($(this).find('.dragbox-content').css('display') == "none")
                    collapsed = 1;
                //Create Item object for current panel  
                var item = {
                    id: $(this).attr('id'),
                    collapsed: collapsed,
                    order: i,
                    column: columnId
                };
                //Push item object into items array  
                items.push(item);
            });
        });
        //Assign items array to sortorder JSON variable  
        var sortorder = { items: items };

        $.ajax({
            url: "/Handlers/SaveWidgets.ashx",
            type: "POST",
            contentType: "application/json; charset=uft-8",
            dataType: "json",
            data: JSON.stringify(sortorder),
            success: function (response) {
                $("#console").html('<div class="success">Dashboard Saved</div>').css('visibility', 'visible').fadeTo(600, 1);
                setTimeout(function () {
                    $('#console').delay(500).fadeTo(600, 0);
                }, 1000);
            },
            error: function (error) {
                $("#console").html('<div class="fail">Dashboard was not saved!</div>').css('visibility', 'visible').fadeTo(600, 1);
                setTimeout(function () {
                    $('#console').delay(500).fadeTo(600, 0);
                }, 1000);
            }
        }); 

和我的处理程序..

SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["dboCao"].ConnectionString);

    string userId;

    public void ProcessRequest(HttpContext context)
    {
        string userName = context.User.Identity.Name;

        conn.Open();

        using (SqlCommand cmdUserId = new SqlCommand("SELECT UserId FROM tUser WHERE UserName = @UserName", conn))
        {
            cmdUserId.Parameters.AddWithValue("@UserName", userName);
            userId = Convert.ToString(cmdUserId.ExecuteScalar());

            System.Diagnostics.Debug.Write(userId);
        }

        String json = String.Empty;
        // you have sent JSON to the server
        // read it into a string via the input stream
        using (StreamReader rd = new StreamReader(context.Request.InputStream))
        {
            json = rd.ReadToEnd();
        }

        // create an instance of YourDataModel from the
        // json sent to this handler
        SaveWidgetsDAL data = null;
        DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(SaveWidgetsDAL));
        using (MemoryStream ms = new MemoryStream())
        {
            byte[] utf8Bytes = Encoding.UTF8.GetBytes(json);
            ms.Write(utf8Bytes, 0, utf8Bytes.Length);
            ms.Position = 0;
            data = serializer.ReadObject(ms) as SaveWidgetsDAL;
        }
        // update the DB and
        // send back a JSON response
        int rowsUpdated = 0;

        foreach (var item in data.wdata)
        {
            string itemTitle = item.Title.Replace("FeaturedContent_", "");
            string itemColumn = item.ColumnId.Replace("FeaturedContent_column", "");

            using (SqlCommand cmd = new SqlCommand("UPDATE tWidgets SET Title = @Title, SortNo = @SortNo, ColumnId = @ColumnId, Collapsed = @Collapsed "
                + "WHERE UserId = @UserId AND Title = @Title;", conn))
            {
                cmd.Parameters.AddWithValue("@ColumnId", itemColumn);
                cmd.Parameters.AddWithValue("@Title", itemTitle);
                cmd.Parameters.AddWithValue("@SortNo", item.SortNo);
                cmd.Parameters.AddWithValue("@Collapsed", item.Collapsed);
                cmd.Parameters.AddWithValue("@UserId", userId);
                rowsUpdated = cmd.ExecuteNonQuery();
            }
        }

        conn.Close();

        context.Response.ContentType = "application/json";
        context.Response.Write("{ \"rows_updated\": " + rowsUpdated + " }");
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

更新2:

通过以下解决方案,我无法让它发挥作用。然后我意识到当我更新小部件信息时,我不得不从列和标题中删除FeaturedContent_column和FeaturedContent_。所以我想我需要把它们放回去!

for (var i = 0; i < te.d.length; i++) {
    $('#FeaturedContent_column' + te.d[i].ColumnId).append($('#FeaturedContent_' + te.d[i].Title));
    if (te.d[i].Collapsed) {
                        //collapse
        $('#' + te.d[i].Title).children('.dragbox-content').css('display') == "none";
    }
 }

1 个答案:

答案 0 :(得分:1)

这应该这样做:

     for (var i = 0; i < te.d.length; i++) {
         $('#column'+te.d[i].ColumnId).append($('#'+te.d[i].Title));
         if (te.d[i].Collapsed)
         {
             //collapse
             $('#'+te.d[i].Title).children(".dragbox-content').css('display') = "none";
         }
     }

这将选择正确的列,并根据数组的排序将小部件附加到它。

$('#column'+te.d[i].ColumnId):jQuery的通用$函数允许我们通过各种选择器选择DOM中的元素。由于您的小部件有ID,我们使用id选择器#。在这种情况下,我们将索引附加到字符串列以构建正确的列选择器。

选择正确的列后,我们会使用.append将小部件附加到其中,并提供$('#'+te.d[i].Title)选择的元素。这会从先前位置移除元素,并将其添加到此列(div)。