use*_*786 2 html javascript css jquery
因此,这是我要使用的拨动开关的功能,我正在使用https://metroui.org.ua/inputs.html ,我要尝试做的是更改开关/复选框之前的标签,表示已选中或未选中。如果单击标签,它将更改开关,但文本不会更改。JavaScript:
$(document).ready(function() {
$('#front_set').click(function() {
if ($(this).is(':checked')) {
$(this).siblings('label').html('checked');
} else {
$(this).siblings('label').html(' not checked');
}
});
});Run Code Online (Sandbox Code Playgroud)
<label for="front_set">checked</label>
<label class="switch-original right">
<input type="checkbox" id="front_set">
<span class="check"></span>
</label>Run Code Online (Sandbox Code Playgroud)
问题:标签不是所单击复选框的同级,因此您不会使用来找到它siblings。该标签实际上是作为复选框父级的标签的同级标签。
解决方案:使用其他选择器查找标签,因此它们的相对位置不再重要。使用,label[for="xyz"]您可以确切地找到绑定到复选框xyz的标签,而不管其在文档中的位置如何。这也使您的代码更加灵活,因为如果您重新组织DOM,它不会立即中断。
var $myLabel = $('label[for="' + this.id + '"]');
$myLabel.html( $(this).is(':checked') ? 'checked' : ' not checked');
Run Code Online (Sandbox Code Playgroud)
var $myLabel = $('label[for="' + this.id + '"]');
$myLabel.html( $(this).is(':checked') ? 'checked' : ' not checked');
Run Code Online (Sandbox Code Playgroud)
$(document).ready(function() {
$('#front_set').click(function() {
var $myLabel = $('label[for="' + this.id + '"]');
$myLabel.html( $(this).is(':checked') ? 'checked' : ' not checked');
});
});Run Code Online (Sandbox Code Playgroud)