1

I would like to add a simple "delete button" to each list item. The list element holds barcodes loaded from some table and I would like to add delete functionality to each barcode.

The ideal solution would be a simple X button in the right center corner of each list item. When the user would click it, a dialog would appear asking to confirm delete action. If clicked cancel nothing would happen, but if clicked confirm the barcode should be: 1.deleted in table and 2.removed from list - or refresh the page.

Since I have no experience with jQuery I am kindly asking if someone can help me out. It is an ASP.NET application and here is the code:

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Entry.aspx.vb" Inherits="KPIP_Entry" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Entry</title>
    <link href="../App_Themes/Outlook/KPIP.css" rel="stylesheet" type="text/css" />
    <style type="text/css">
        #entryForm
        {
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: #c3daf9;
            background-image: url("../App_Themes/Outlook/Base/CoolTable_Background.png");
            background-repeat: repeat-x;
        }

        #attachments
        {
            width: 320px;
            overflow: auto;
            height: 100%;
            float: left;
        }

        #attachments span.tetradaGroupLabel:first-child
        {
            margin-top:16px;
        }

        ul#barcodesList
        {
            display: block;
            width: 320px;
            overflow: auto;
        }

        ul#barcodesList > :first-child
        {
            border-top: 1px solid #2557AD;
            margin-top: 20px;
        }

        ul#barcodesList > li
        {
            list-style: none;
            margin-left: 20px;
            margin-right: 20px;
            border-collapse: separate;
            border-left: 1px solid #2557AD;
            border-right: 1px solid #2557AD;
            border-bottom: 1px solid #2557AD;
            color: #2557AD;
            height: 20px;
            background: #e7f0fe;
            cursor: pointer;
            padding-left: 12px;
            padding-top: 6px;
        }

        ul#barcodesList > li.clicked
        {
            background: #91B5E7;
            color: #ffffff;
        }

        #entryViewer
        {
            height: 100%;
            border-left: solid 4px #2557AD;
            float: left;
        }

        #dummyPostbackButton
        {
            display: block;
            width: 0px;
            height: 0px;
            overflow: hidden;
            visibility: hidden;
        }

        #upload_main
        {
            margin: 12px 20px 0px 20px;
            float:left;
            clear:both;
        }

        #upload_main .cc_table_container
        {
            max-width: 278px;
        }

        #barcodesShadow 
        {
            width: 280px; 
            margin-bottom: 20px;
            margin-left: 20px;
        }

        span.tetradaGroupLabel 
        {
            display:block;
            margin-top:12px;
            padding-left:32px;
            float:left;
        }
    </style>
    <script type="text/javascript" src="../Script/jquery-1.4.2.min.js"></script>
    <script type="text/javascript" src="Script/kpip.js"></script>
    <script type="text/javascript">
        var barcodes = { <%# BarcodeArray %> }

        kpip.viewAttachment = function (url) {
            $("#entryViewer").attr("src", "../Viewer.aspx?image=" + url);
        }

        function resizeViewer() {
            $("#entryViewer").hide();
            $("#attachments").hide();
            $("#entryViewer").width($("#entryForm").width() - 320 - 4);
            $("#entryViewer").height($("#entryForm").height() - $("#header").height() - 4);
            $("#attachments").height($("#entryForm").height() - $("#header").height() - 4);
            $("#attachments").show();
            $("#entryViewer").show();
        }

        $(function () {
            $.each(barcodes, function(key, value) {
                $("#barcodesList").append("<li>" + key + "</li>");
            });

            if ($("#barcodesList").children().size() > 0) {
                $("#barcodesList").after('<div id="barcodesShadow" class="cc_panelShadow"></div>');
            }

            $("#barcodesList > li").click(function () {
                $("#barcodesList > li").removeClass("clicked");
                $(this).addClass("clicked");
                $("#selectedBarcode").val($(this).text());

                var params = '{ barcode : "' + $(this).text() + '", path : "' + barcodes[$(this).text()] + '" }';
                $.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    url: "Entry.aspx/Attach",
                    dataType: "json",
                    data: params,
                    success: function () {
                        $("#dummyPostbackButton").click();
                    },
                    error: function (request, status, error) {
                        alert("Error attaching barcode file.");
                    }
                });
            });

            $(window).bind("resize", function () {
                setTimeout(function () { resizeViewer(); }, 10);
            });
            setTimeout(function () { resizeViewer(); }, 10);

            $("#barcodesList > li").each(function () {
                if ($(this).text() != $("#selectedBarcode").val()) { return; }
                $(this).addClass("clicked");
            });
        });

    </script>
</head>
<body>
    <form id="entryForm" runat="server">
    <div id="header" class="ContentHeader">
        <asp:Label runat="server" CssClass="ContentHeaderLabel" Text="<%$ Resources: Header.Text %>"/>
    </div>
    <div id="attachments">
        <asp:Label class="tetradaGroupLabel" runat="server" Text="<%$ Resources: AttachmentsPanel.Text %>" />
        <tetrada:MultiUpload ID="upload" runat="server" />
        <asp:Panel ID="BarcodesListPanel" runat="server">
            <asp:Label class="tetradaGroupLabel" runat="server" Text="<%$ Resources: BarcodesPanel.Text %>" />
            <ul id="barcodesList"></ul>
        </asp:Panel>
        <asp:HiddenField ID="selectedBarcode" runat="server" />
        <asp:Button ID="dummyPostbackButton" runat="server" CausesValidation="false" />
    </div>
    <iframe id="entryViewer" frameborder="0" runat="server"></iframe>
    </form>
</body>
</html>

And the code behind:

Imports System.Collections.Generic
Imports System.IO
Imports System.Web.Services

Imports Tetrada.Kpip.Web
Imports Tetrada.Kpip.Domain
Imports Tetrada.Kpip.Service
Imports Tetrada.Kpip.Web.Controls

Partial Class KPIP_Entry
    Inherits KpipPage

    Private _barcodes As IList(Of BarcodeAttachment) = New List(Of BarcodeAttachment)()

    Private ReadOnly Property Barcodes() As IList(Of BarcodeAttachment)
        Get
            Return _barcodes
        End Get
    End Property

    Protected Sub New()
        If Not KpipConfiguration.IsBarcodeSourceEnabled Then Return
        _barcodes = New RepositoryFactory().GetDocumentRepository().GetAvailableBarcodes(KpipConfiguration.BarcodesSection.Source.Value, KpipConfiguration.BarcodesSection.Table.Value)
    End Sub

    Public ReadOnly Property BarcodeArray As String
        Get
            Dim result As StringBuilder = New StringBuilder()
            For Each barcode As BarcodeAttachment In Barcodes
                result.AppendFormat("""{0}"":""{1}"", ", barcode.Barcode, barcode.Path.Replace("\", "\\").Replace("\", "\\"))
            Next
            If Barcodes.Count = 0 Then Return result.ToString()
            Return result.Remove(result.Length - 2, 2).ToString()
        End Get
    End Property

    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        BarcodesListPanel.Visible = KpipConfiguration.IsBarcodeSourceEnabled
        DataBind()
    End Sub

    Protected Sub DummyPostbackButton_Click(sender As Object, e As System.EventArgs) Handles dummyPostbackButton.Click
        If Not upload.HasFiles() Then Return
        Dim manager As TemporaryPathManager = New TemporaryPathManager()
        ClientScript.RegisterStartupScript(Me.GetType(), "showAttachment", String.Format("$(function() {{ kpip.viewAttachment('{0}'); }});", manager.ToAbsoluteUrl(upload.Guid, upload.UploadedFiles(0))), True)
    End Sub

    <WebMethod(EnableSession:=True)> _
    Public Shared Sub Attach(ByVal barcode As String, ByVal path As String)
        Dim manager As TemporaryPathManager = New TemporaryPathManager()
        Dim name As String = IO.Path.GetFileName(path)
        If Not manager.IsPathCreated(MultiUpload.CurrentGuid) Then manager.CreatePath(MultiUpload.CurrentGuid)
        MultiUpload.Clear()
        File.Copy(path, manager.ToAbsolutePath(MultiUpload.CurrentGuid, name))
        MultiUpload.AddFile(name)
        KpipSession.SelectedBarcode = barcode
    End Sub
End Class

Thank you in advance.

EDIT:

I used span instead of the button and i got the desired effect. Now the problem is when clicking the span the list item click event fires instead of the span click event. What am I doing wrong?

The code:

deleteButton = $('<span />').addClass('deleteButton').text('Delete');
$('ul#barcodesList li').append(deleteButton);

With style:

ul#barcodesList > li > span
{
    float: right;
    color: #2557AD;
    display:block;
}

ul#barcodesList > li > span:hover
{
    display:block;
    color: red;
}

The click event:

    $('#barcodesList > li > span').click(function(){
        function() {
            alert("hi");
        }
    });

EDIT2:

I have added this function that stops the parent from firing the click event:

    $("#barcodesList > li > span").click(function(e) {
       e.stopPropagation();
       $('#dialog').dialog('open');
    });

It works now. Thank you.

4

1 回答 1

2

您可以使用 jQuery 的append()prepend()和函数将元素添加到另一个元素appendTo()prependTo()

您可以将纯 html 添加为字符串,也可以使用 jQuery 构建元素,这看起来更简洁。

例如

deleteButton = $('<button />').addClass('deleteButton').text('Delete');

// using appendTo/prependTo:
deleteButton.appendTo('ul#barcodesList li'); // adds it on the end of the element you've selected

// using append/prepend:
$('ul#barcodesList li').append(deleteButton); // you can pass in the jquery object here
于 2013-07-17T08:30:59.137 回答