Мой html выглядит так:
<table class="ListCheck">
<tbody>
<tr>
<td>
<span class="listitem">
<input name="ctl00$MainContent$List$0" class="location" id="MainContent_List_0" type="checkbox">
<label for="MainContent_List_0">test</label></span>
</td>
<td>
<span class="listitem">
<input name="ctl00$MainContent$List$1" class="location" id="MainContent_List_1" type="checkbox">
<label for="MainContent_List_1">test</label></span>
</td>
<td>
<span class="listitem">
<input name="ctl00$MainContent$List$2" class="location" id="MainContent_List_2" type="checkbox">
<label for="MainContent_List_2">test</label></span>
</td>
</tr>
</tbody>
</table>
Я пытаюсь добавить javascript, чтобы добавить класс на ярлыке, чтобы применить некоторый css при выборе флажка
мой сценарий:
<script type='text/javascript'>
$('.listitem').each(function () {
$(this).children("input").addClass("location");
if ($(this).children("input").is(":checked"))
{
$(this).children('label').addClass("checked");
} else {
$(this).children('label').removeClass("checked");
}
});
</script>
Но по какой-то причине он не добавляет класс на метку во время выполнения. Посмотрите мой код и дайте мне знать, чего я не вижу. ТИА.
Вы можете использовать метод next()
для доступа к соответствующему <label>
следующим образом:
$('input[type="checkbox"]').click(function () {
$(this).next().toggleClass("checked");
});
Попробуйте использовать свой код с помощью
$( ".target" ).change(function() {
alert( "Handler for .change() called." );
});
так
<script type='text/javascript'>
$('.listitem').each(function () {
$(this).children("input").addClass("location");
$(this).children("input").change(function() {
if ($(this).children("input").is(":checked"))
{
$(this).children('label').addClass("checked");
} else {
$(this).children('label').removeClass("checked");
}
});// missing bracket ;)
});
</script>
Я немного изменил свой код, это было неправильно, если я понял вас правильно.
$('.location').click(function() {
if ($(this).is(":checked"))
{
console.log('added');
$(this).closest('label').addClass("checked");
} else {
console.log('removed');
$(this).closest('label').removeClass("checked");
}
});
Ваш код javascript должен выглядеть так:
$('.listitem').click(function () {
$(this).children("input").addClass("location");
if ($(this).children("input").is(":checked"))
{
$(this).children('label').addClass("checked");
} else {
$(this).children('label').removeClass("checked");
}
});
клик применяется ко всем элементам, найденным селектором.