检查ul list on_change中是否存在HTML属性(复选框)



我想知道如何使用jQuery查看checkbox元素的HTML属性(如此处的cat(是否在元素的<ul>列表中

// checkbox like so, cat is the string I want
<input type="checkbox" name="country_code" data-cat="city_inf">
// list of elements containing my categories (when one element of it is checked in HTML code)
<ul id="sortable" class="ul_drag_el">
<li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Cat name 1</li>
<li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Cat name 2</li>
<li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>etc..</li>
</ul>

另一个问题是,如果我想计算一个类别中有多少元素被选中以显示/隐藏li类别名称,我应该按名称列出每个被选中的元素,还是只做一个计数器(仍在jQuery中(。

目前我在jQuery中只有这个,但我真的不知道如何开始。

$("input[type='checkbox']").change(function(){
let text_to_append = "<li className='ui-state-default'><span className='ui-icon ui-icon-arrowthick-2-n-'>"
text_to_append += $(this).attr('name');
text_to_append += "</span>"
if(this.checked){
$('.ul_drag_el').append(text_to_append)
}  
})

编辑:它最终与一起工作

$("input[type='checkbox']").change(function(){
let this_name = $(this).attr('data-cat')
let text_to_append = "<li className='ui-state-default' data-cat='"
text_to_append += this_name
text_to_append += "'><span className='ui-icon ui-icon-arrowthick-2-n-'>"
text_to_append += this_name
text_to_append += "</span>"
if(this.checked){
$('.ul_drag_el').append(text_to_append)
}else{
$('#sortable li').each(function(){
if($(this).attr('data-cat') == this_name){
$(this).remove();
}
})
}
})

您也可以简单地将数据属性添加到值为data-catli标记中。然后,无论何时选中复选框,您都可以简单地检查该data-cat是否已经存在或没有使用$("#ul").find("[data-name=" + $(this).data('cat') + "]").length == 0)(如果是(,只需删除它们或添加新的li

演示代码 :

$("input[type='checkbox']").change(function() {
//check if checkbox is checked & that doesn't exist inside ul
if ((this.checked) && ($("#ul").find("li[data-name=" + $(this).data('cat') + "]").length == 0)) {
let text_to_append = "<li className='ui-state-default' data-name='" + $(this).data('cat') + "'><span className='ui-icon ui-icon-arrowthick-2-n-'>"
text_to_append += $(this).attr('name');
text_to_append += "</span></li>"
$('.ul_drag_el').append(text_to_append)
} else {
//remove them
$("li[data-name=" + $(this).data('cat') + "]").remove()
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="city_inf" data-cat="city_inf">
<input type="checkbox" name="abcs" data-cat="abcs">
<ul id="sortable" class="ul_drag_el">
</ul>

$(document).on('change', '.country_code', function () {
var cat = "";
if ($(this).is(':checked')) {
cat = $(this).attr('data-cat');
}
$('#sortable li').each(function () {
if ($(this).attr('data-cat') == cat) {
$(this).show()
} else {
$(this).hide()
}
})
})

最新更新