在jQuery中添加一个按钮以列出项目并触发click事件
Posted
技术标签:
【中文标题】在jQuery中添加一个按钮以列出项目并触发click事件【英文标题】:Adding a button to list item in jQuery and fireing the click event 【发布时间】:2013-07-15 16:59:11 【问题描述】:我想为每个列表项添加一个简单的“删除按钮”。 列表元素包含从某个表加载的条形码,我想为每个条形码添加删除功能。
理想的解决方案是在每个列表项的右上角添加一个简单的 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 而不是按钮,我得到了想要的效果。现在的问题是,当单击跨度时,会触发列表项单击事件而不是跨度单击事件。我做错了什么?
代码:
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:
我已经添加了这个函数来阻止父级触发点击事件:
$("#barcodesList > li > span").click(function(e)
e.stopPropagation();
$('#dialog').dialog('open');
);
现在可以了。谢谢。
【问题讨论】:
【参考方案1】:您可以使用 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
【讨论】:
感谢您的提示。请查看我的编辑...我使用了跨度,因为我在定位按钮时遇到了问题。你能帮我弄清楚为什么我不能触发跨度点击事件吗? 如果您使用的是$('span').click(...)
,那么这是因为您正在动态添加跨度,因此事件之后不会附加。您需要使用 jQuery 的 on()
api.jquery.com/on 以便在动态添加的元素上传播事件。以上是关于在jQuery中添加一个按钮以列出项目并触发click事件的主要内容,如果未能解决你的问题,请参考以下文章