HTML:
<div class="checkbox">
<label for="input-1">
<input type="checkbox" id="input-1" class="js-wpv-filter-trigger" name="wpv-known-as[]" value="input-1">input-1</label>
</div>
<div class="checkbox">
<label for="input-2">
<input type="checkbox" id="input-2" class="js-wpv-filter-trigger" name="wpv-known-as[]" value="input-2">input-2</label>
</div>
<div class="show-labels">
</div>单击input时,我希望复制它的父label并将其附加到外部.show-labels div。但是,当我再次单击它时,我希望将复制的label从.show-labels中移除-等等,以供下一个input使用。
我试过了,但没成功:
$('.checkbox input').click(function() {
var thisval = $(this).val();
$(this).parent().addClass(thisval);
var copy = $(this).parent().html();
var clicks = $(this).data('clicks');
if (clicks) {
$(".show-labels").append(copy);
} else {
$(".show-labels label").hasClass(thisval).remove();
}
$(this).data("clicks", !clicks);
});发布于 2018-11-30 07:21:35
您可以使用无性系克隆元素,然后在未选中时删除。
我还提供了演示,以便只获取文本。
$('.checkbox input').on("change",function() {
if($(this).is(":checked")){
var label= $(this).closest('label').clone();
$('.show-labels').append(label);
}
else{
$(".show-labels").find('label[for="' + $(this).attr('id') + '"]').remove();
}
});
$('.checkbox input').on("change",function() {
if($(this).is(":checked")){
var label= $(this).closest('label').text();
$('.show-labelsonlytext').append("<span for="+$(this).attr("id")+">"+label+ "</span>");
}
else{
$(".show-labelsonlytext").find('span[for="' + $(this).attr('id') + '"]').remove();
}
});<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="checkbox">
<label for="input-1">
<input type="checkbox" id="input-1" class="js-wpv-filter-trigger" name="wpv-known-as[]" value="input-1">input-1</label>
</div>
<div class="checkbox">
<label for="input-2">
<input type="checkbox" id="input-2" class="js-wpv-filter-trigger" name="wpv-known-as[]" value="input-2">input-2</label>
</div>
with input
<div class="show-labels">
</div>
without input
<div class="show-labelsonlytext">
</div>
发布于 2018-11-30 07:12:43
试试这个:
$('.checkbox input').click(function() {
var copy = $(this).closest(".checkbox").find("label").html();
var clicks = $(this).data('clicks');
if (clicks) {
$(".show-labels").append(copy);
} else {
$(".show-labels label").remove();
}
$(this).data("clicks", !clicks);
});发布于 2018-11-30 07:22:19
尝尝这个
$('.checkbox input').click(function() {
let name = $(this).parent().attr('for');
if($(this).is(':checked')) {
const item = $('<div/>').attr('data-item', name).text(name);
$('.show-labels').append(item);
}
else {
$('.show-labels div[data-item='+name+']').remove();
}
});https://stackoverflow.com/questions/53552778
复制相似问题