首页 文章

在jQuery中添加按钮以列出项目并触发click事件

提问于
浏览
1

我想为每个列表项添加一个简单的“删除按钮” . list元素包含从某些表加载的条形码,我想为每个条形码添加删除功能 .

理想的解决方案是每个列表项右下角的简单X按钮 . 当用户单击它时,将出现一个对话框,要求确认删除操作 . 如果点击取消,则不会发生任何事情,但如果点击确认条形码应该是:1 . 删除表格,2 . 从列表中删除 - 或刷新页面 .

由于我没有使用jQuery的经验,我很乐意询问是否有人可以帮助我 . 它是一个ASP.NET应用程序,这里是代码:

<%@ 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>

而背后的代码:

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

先感谢您 .

编辑:

我用span而不是按钮,我得到了理想的效果 . 现在的问题是,单击列表项单击事件触发的 Span 而不是 Span 单击事件 . 我究竟做错了什么?

代码:

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

风格:

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

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

点击事件:

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

EDIT2:

我添加了这个函数来阻止父进程触发click事件:

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

它现在有效 . 谢谢 .

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
    

相关问题