簡體   English   中英

如何在列表框中添加關閉按鈕

[英]How to add Close Button in Listbox

我正在使用文本框將城市名稱以及我想添加關閉按鈕的城市名稱添加到列表框中,因此我可以輕松地從列表框中刪除城市名稱。
下面的圖像是為了更好地理解 在此處輸入圖片說明

的HTML

<asp:TextBox ID="txtcity" runat="Server"></asp:TextBox>
<asp:Button ID="btnAddcity" runat="server" Text="Add" />
<asp:ListBox ID="listBoxcity" runat="server"></asp:ListBox>
<span id="spcity"></span>

jQuery查詢

$("#btnAddcity").click(function () {
  var txt = $("#txtcity").val();
  $('[id$=listBoxcity]').show();
  var alreadyExist = false;
  $('[id$=listBoxcity] option').each(function () {
  if ($(this).val() == txt) {
    $("#spcity").text('City alread exists');
     alreadyExist = true;
     return;
  }
});
if (!alreadyExist) {
  $('[id$=listBoxcity]').append($('<option></option>').attr('value', txt).text(txt));
 }
});

我刪除了選項選擇,因為您不能在選項上添加刪除按鈕。 如果您嘗試執行此操作,請看一下:

 $("#btnAddcity").click(function () { var txt = $("#txtcity").val(); $('[id$=listBoxcity]').show(); var alreadyExist = false; $('[id$=listBoxcity] option').each(function () { if ($(this).val() == txt) { $("#spcity").text('City alread exists'); alreadyExist = true; return; } }); if (!alreadyExist) { $('[id$=listBoxcity]').append($('<span></span>').attr('value', txt).text(txt)); $('[id$=listBoxcity]').append($('<a href="#" class="delete">x</a><br>')); } }); $(document).on('click', 'a.delete', function(event){ $(this).prev('span').remove(); $(this).next('br').remove(); $(this).remove(); }); 
 a.delete { margin-left: 10px; width: 20px; height: 20px; background: #82854C; border-radius: 100%; text-align: center; display: inline-block; color: #fff; vertical-align: middle; text-decoration: none; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script> <table> <tr> <td><input id='txtcity' type="text" /></td> <td><input id='btnAddcity' type='button' value='Add' /></td> </tr> </table> <!-- <select id='listBoxcity' multiple="multiple" style='width:300px; height:100px;'> </select> --> <div id='listBoxcity' multiple="multiple" style='width:300px; height:100px;'> </div> <span id='spcity'></span> 

這個片段是對我工作:)

$(document).ready(function(){
$("#btnAddcity").click(function () {
  var txt = $("#txtcity").val();
  $('[id$=listBoxcity]').show();
  var alreadyExist = false;
  $('[id$=listBoxcity] option').each(function () {
  if ($(this).val() == txt) {
    $("#spcity").text('City alread exists');
     alreadyExist = true;
     return;
  }
});
var count = 0;
if (!alreadyExist) {
count++;
  $('[id$=listBoxcity]').append($('<span></span>').attr('value', txt).text(txt));
   $('[id$=listBoxcity]').append($('<div class="delete">x</div><br>'));
 }

 $('.delete').on('click',function(e){
    console.log($(this).closest('span'));
   $(this).next('br').remove();
   $(this).prev('span').remove();
   $(this).remove(); 
  });
});

});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM