我正在使用文本框将城市名称添加到列表框中,以及我想添加关闭按钮的城市名称,这样我就可以轻松地从列表框中删除城市名称。
下图是为了更好地理解
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>
关于javascript - 如何在列表框中添加关闭按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37832987/