2016-10-14 7 views
1

Stripped down working jsfiddleJQuery изменить цвет фона на отдельные функции

У меня есть строки быть выделены, если их флажок. Он работает на одном столе, но по какой-то причине я не понимаю, почему он не делает то же самое с другой. Все остальные функции - это именно то, что я хочу.

$(document).ready(function() { 

    $('#myteam').on('change', '[type=checkbox]', function() { 
    var $this = $(this); 
    var row = $this.closest('tr'); 
    if ($this.prop('checked')) { // move to top 
     row.insertBefore(row.parent().find('tr:first-child')) 
    } else { // move to bottom 
     row.insertAfter(row.parent().find('tr:last-child')) 
    } 
    }); 
    $('#otherteam').on('change', '[type=checkbox]', function() { 
    var $this = $(this); 
    var row = $this.closest('tr'); 
    if ($this.prop('checked')) { // move to top 
     row.insertBefore(row.parent().find('tr:first-child')) 
    } else { // move to bottom 
     row.insertAfter(row.parent().find('tr:last-child')) 
    } 
    }); 
    $('td:first-child input').change(function() { 
    $(this).closest('#myteam tr').toggleClass("highlight", this.checked); 
    }); 
    $('td:first-child input').change(function() { 
    $(this).closest('#otherteam tr').toggleClass("highlight", this.checked); 
    }); 
}); 
+0

Вы можете создать общий ресурс html – Arvin

+0

jsfiddle ведет себя правильно? – Terminus

+0

все работает хорошо, за исключением случаев, когда вы проверяете коробку на правой стороне, строка не подсвечивается, как на левой стороне. – Josh

ответ

0

Вот проблема $('td:first-child input'), удалить :first-child во втором случае изменение будет то, что вам нужно, потому что это не первый ребенок.

2

Как K.Angel7 упоминается, незначительная проблема с селектором jQuery.

Я установил jsfiddle и здесь вы идете: http://jsfiddle.net/Manoj85/k1xfehrq/98/

$('#otherteam td input').change(function() { 
    console.log("Other Team"); 
    $(this).closest('#otherteam tr').toggleClass("highlight", this.checked); 
    }); 
    $('#myteam td input').change(function() { 
    console.log("My Team"); 
    $(this).closest('#myteam tr').toggleClass("highlight", this.checked); 
    }); 

Всегда, рассмотреть вопрос о добавлении конкретного родителя, в вашем случае, #myteam и #otherteam. Было бы лучше для поддержания любых обновлений в будущем.

Надеюсь, это поможет.

1

Одним из решений было бы сделать ваш селектор более точным.

$('#myteam td:first-child input').change(function() { 
    $(this).closest('#myteam tr').toggleClass("highlight", this.checked); 
}); 
$('#otherteam td:first-child input').change(function() { 
    $(this).closest('#otherteam tr').toggleClass("highlight", this.checked); 
}); 

Однако было бы проще переместить переключатель подсветки в другую функцию изменения.

$('#myteam').on('change', '[type=checkbox]', function() { 
    var $this = $(this); 
    var row = $this.closest('tr'); 
    if ($this.prop('checked')) { // move to top 
    row.insertBefore(row.parent().find('tr:first-child')) 
    } else { // move to bottom 
    row.insertAfter(row.parent().find('tr:last-child')) 
    } 
    $this.toggleClass("highlight", this.checked); 
}); 
$('#otherteam').on('change', '[type=checkbox]', function() { 
    var $this = $(this); 
    var row = $this.closest('tr'); 
    if ($this.prop('checked')) { // move to top 
    row.insertBefore(row.parent().find('tr:first-child')) 
    } else { // move to bottom 
    row.insertAfter(row.parent().find('tr:last-child')) 
    } 
    $this.toggleClass("highlight", this.checked); 
}); 

Это должно ответить на вопрос. Но я заметил, что функции могут быть упрощены. Вы можете заменить весь код размещен только с этими линиями:

$(document).ready(function() { 
    $('#myteam, #otherteam').find(':checkbox').change(function() { 
    var $this = $(this); 
    var row = $this.closest('tr'); 
    if (this.checked) { // move to top 
     row.prependTo(row.parent()) 
    } else { // move to bottom 
     row.appendTo(row.parent()) 
    } 
    row.toggleClass("highlight", this.checked); 
    }); 
}); 

Обратите внимание, что :checkbox является jquery-defined psuedo-selector

Here's a fiddle где я переработан еще некоторые вещи.

+0

отлично, я предположил, что существует способ сделать его более эффективным .., но для моего уровень я должен был сделать их отдельно, чтобы заставить их работать сначала – Josh

+0

@ Josh умное мышление – Terminus

Смежные вопросы