[英]jQuery toggle text in div based on checkbox state
I'm still in the process of learning jQuery and have run into something I can't seem to solve. 我仍在学习jQuery的过程中,遇到了我似乎无法解决的问题。 I'm trying to toggle the label of a checkbox in a div located elsewhere on the page.
我正在尝试在位于页面其他位置的div中切换复选框的标签。 So far I've managed to append the label only if the checkbox is unchecked, but I can't figure out how to remove the text for that filter only if it becomes unchecked.
到目前为止,我仅在未选中复选框的情况下设法添加标签,但是我无法弄清楚如何仅在未选中该过滤器时删除该过滤器的文本。 Any advice?
有什么建议吗?
JQUERY: JQUERY:
$('.filter-single').on('click', function () {
if ($('.filter-single input').is(':checked')) {
$('<li>'+$(this).text()+' / </li>').appendTo('.filters-current');
} else {
// what goes here?
}
});
FILTER HTML: 过滤HTML:
<div class="checkbox filter-single">
<input type="checkbox" value=".rain"/>
<label>Rain</label>
</div>
LABEL HTML: 标签HTML:
<div class="filter-details">
<span class="filter-title">Filters:</span>
<ul class="filters-current"></ul>
</div>
You can use :contains() to look for the corresponding LI and then .remove() , also i would assign the click handler to the input itself instead of the container like this: 您可以使用:contains()查找相应的LI,然后使用.remove() ,我也将点击处理程序分配给输入本身,而不是像这样的容器:
$('.filter-single input').on('click', function () {
if ($(this).is(':checked')) {
$('<li>' + $(this).next("label").text() + ' /</li>').appendTo('.filters-current');
} else {
$(".filters-current").find("li:contains('" + $(this).next("label").text() + " /')").remove();
}
});
Something like: 就像是:
$('.filters-current').html("");
This should set the inner html as empty string. 这应该将内部html设置为空字符串。
I guess you are trying to implement several filters, if not Taleeb's answer should work. 我猜您正在尝试实现多个过滤器,如果Taleeb的答案不起作用。 If you are indeed looking for several, you could try something like this:
如果您确实要寻找几个,则可以尝试以下操作:
var filters={};
$('input:checkbox').on('click', function () {
var filter_name = $(this).siblings("label").text();
if($(this).is(":checked")){
filters[filter_name]=true;
}else{
filters[filter_name]=false;
}
displayFilters();
});
function displayFilters(){
$(".filters-current").html("");
console.log(filters)
for (var filter in filters){
if(filters[filter]){
$(".filters-current").append("<li>"+filter+"</li>")
}
}
}
Demo: http://jsfiddle.net/juvian/X65wv/ 演示: http : //jsfiddle.net/juvian/X65wv/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.