在属性中查找子字符串
Looking for a substring in an attribute
我已将所有选中的复选框的 ID 放入一个数组并将其转换为字符串。现在我想遍历 HTML 中的所有标签,看看 for
属性的值是否与所有 id 的字符串中的某些内容匹配,如果匹配更改 css标签。提前谢谢你。
var $all_labels = $('.filter-choices label')
$all_labels.each(function(){
var self_item = $(this)
if( self_item.attr('for').is(checked_items_ids_string) === true){
self_item.css('color','white')
}
});
First I've put the id's from all checked checkboxes into an array and
converted it so a string
Now I want to loop over all the labels in my HTML and see if value of
the for attribute matches with something in the string of all ids.
试试
var checkedItems = []; //assuming this is already populated
$( "label[for]" ).each( function(){
var idVal = $(this).attr( "for" );
if ( $("#" + idVal).length > 0 && checkedItems.indexOf( idVal ) != -1 )
{
//element with id exists
$(this).css('color','white')
}
})
也许这种方法也会有帮助:
$('button').click(function () {
$('input').each(function () {
if ($(this).is(':checked'))
$(this).prev('label').css("color", "red")
else
$(this).prev('label').css("color", "black")
})
})
<label for="i1">Input 1: </label>
<input type="checkbox" id="i1">
<br>
<label for="i1">Input 1: </label>
<input type="checkbox" id="i1">
<br>
<label for="i1">Input 1: </label>
<input type="checkbox" id="i1">
<br>
<label for="i1">Input 1: </label>
<input type="checkbox" id="i1">
<br>
<label for="i1">Input 1: </label>
<input type="checkbox" id="i1">
<br>
<button>Change labels</button>
<script src="https://unpkg.com/jquery"></script>
我已将所有选中的复选框的 ID 放入一个数组并将其转换为字符串。现在我想遍历 HTML 中的所有标签,看看 for
属性的值是否与所有 id 的字符串中的某些内容匹配,如果匹配更改 css标签。提前谢谢你。
var $all_labels = $('.filter-choices label')
$all_labels.each(function(){
var self_item = $(this)
if( self_item.attr('for').is(checked_items_ids_string) === true){
self_item.css('color','white')
}
});
First I've put the id's from all checked checkboxes into an array and converted it so a string
Now I want to loop over all the labels in my HTML and see if value of the for attribute matches with something in the string of all ids.
试试
var checkedItems = []; //assuming this is already populated
$( "label[for]" ).each( function(){
var idVal = $(this).attr( "for" );
if ( $("#" + idVal).length > 0 && checkedItems.indexOf( idVal ) != -1 )
{
//element with id exists
$(this).css('color','white')
}
})
也许这种方法也会有帮助:
$('button').click(function () {
$('input').each(function () {
if ($(this).is(':checked'))
$(this).prev('label').css("color", "red")
else
$(this).prev('label').css("color", "black")
})
})
<label for="i1">Input 1: </label>
<input type="checkbox" id="i1">
<br>
<label for="i1">Input 1: </label>
<input type="checkbox" id="i1">
<br>
<label for="i1">Input 1: </label>
<input type="checkbox" id="i1">
<br>
<label for="i1">Input 1: </label>
<input type="checkbox" id="i1">
<br>
<label for="i1">Input 1: </label>
<input type="checkbox" id="i1">
<br>
<button>Change labels</button>
<script src="https://unpkg.com/jquery"></script>