当我检查任何复选框时,我得到li中的值,如果我取消选中第一个复选框,然后选中第二个复选框,我想删除第一个复选框的文本/值,如下所示:
以下是我的代码:
$('input[type="checkbox"]').bind('change', function() {
var alsoInterested = '';
$('input[type="checkbox"]').each(function(index, value) {
if (this.checked) {
/*add*/ /*get label text associated with checkbox*/
alsoInterested += ($('label[for="'+this.name+'"]').html() + ', ');
}
});
if (alsoInterested.length > 0) {
alsoInterested = alsoInterested.substring(0,alsoInterested.length-2);
} else {
alsoInterested = '';
}
console.log(alsoInterested);
var li = $('<li>'+alsoInterested+'<li/>').appendTo('#list');
$("#ul").append(li);
});
$('li').click(function()
{
alert('test');
});
&#13;
li
{
float:left;
width: auto;
background: #ccc;
margin:10px;
display:inline-block;
cursor: pointer;
}
li:hover::after {
content: 'x';
color: white;
margin: 10px;
cursor: pointer;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="bannanasChk" name="bannanasChk" value="N">
<label for="bannanasChk" class="light">Bannanas</label>
<input type="checkbox" id="carChk" name="carChk" value="N">
<label for="carChk" class="light">Car Monkeys</label>
<input type="checkbox" id="apesChk" name="apesChk" value="N">
<label for="apesChk" class="light">Apes</label>
<input type="checkbox" id="repairChk" name="repairChk" value="N">
<label for="repairChk" class="light">Car Repair</label>
<br>
<ul class="list-unstyled" id="list">
</ul>
&#13;
答案 0 :(得分:0)
正如您所见,维护基于已检查/未检查值的列表变得非常复杂,而且很快。
实现这一目标的一种更简单的方法是在更改每个复选框时从所选选项中重新构建一个数组。然后,您可以使用此数组在li
中显示相关的ul
元素,如下所示:
$(':checkbox').on('change', function() {
var $list = $('#list').empty();
var alsoInterested = $(':checkbox:checked').map(function() {
var title = $(this).next('label').text();
$(`<li>${title}</li>`).appendTo($list);
return title;
}).get();
console.log(alsoInterested);
});
&#13;
li {
float: left;
width: auto;
background: #ccc;
margin: 10px;
display: inline-block;
cursor: pointer;
}
li:hover::after {
content: 'x';
color: white;
margin: 10px;
cursor: pointer;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="bannanasChk" name="bannanasChk" value="N">
<label for="bannanasChk" class="light">Bannanas</label>
<input type="checkbox" id="carChk" name="carChk" value="N">
<label for="carChk" class="light">Car Monkeys</label>
<input type="checkbox" id="apesChk" name="apesChk" value="N">
<label for="apesChk" class="light">Apes</label>
<input type="checkbox" id="repairChk" name="repairChk" value="N">
<label for="repairChk" class="light">Car Repair</label><br />
<ul class="list-unstyled" id="list"></ul>
&#13;
请注意,bind()
已过时且已弃用。您应该使用on()
代替,如上例所示。