【问题标题】:Position HTML div based on JSON information根据 JSON 信息定位 HTML div
【发布时间】:2015-02-25 19:23:56
【问题描述】:

我正在创建仪表板,并且能够使用 jQuery、JSON 和通用处理程序将信息保存到我的数据库中。现在,我能够使用 WebService 和 JSON 回调我的数据库信息。我的数据库信息是这样的..

文档准备好后,我使用它从 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>

这就是显示的内容。

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

这就是我的 aspx 页面的样子(只有一个“列”来获得想法)

    <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为" column1" 并位于第一个位置。我不太擅长 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";
    }
 }

【问题讨论】:

    标签: javascript jquery html asp.net json


    【解决方案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)。

    【讨论】:

    • 感谢您的回复!我只是试了一下。我没有收到任何错误,但是在将小部件保存到数据库和页面刷新后,它们没有被加载到它们的新位置。我已验证他们的新位置正在保存,但在页面刷新后,它们又恢复了默认值。有什么建议吗?
    • 我已经更新了我的问题并提供了我如何更新小部件信息。
    • 这是个问题吗?我觉得可能是因为它是在我保存小部件的时候。当我保存小部件时,我必须替换 FeaturedContent_ 和 FeaturedContent_column。要定位它,由于我使用的是内容占位符,我是否必须将它们添加回来?
    • 在我看来您的更新代码将order = index 传递给服务器,但您期望item.SortNo 并且您期望item.Title 而id 被传递。我认为没有任何更新,因为它找不到标题为 null 的数据库行。
    • 它正在更新。问题在于特色内容。我会接受您的回答,因为没有它,我将无法弄清楚!谢谢!
    猜你喜欢
    • 2017-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多