Jquery比较已检查的数据/对象差异

时间:2015-09-15 10:20:19

标签: javascript jquery html css

我试图设置一个复选框来突出显示div内部数据之间的差异,而不是表格。

因此,如果行有差异"单身,单身,结婚"这应该突出显示。

http://jsfiddle.net/Ly61u493/1/

逻辑:

$('.check-diff').click(function() {
if($(this).prop('checked')){
    //highlight status except header
    alert("Bang highlight it...");
} else{
    //unchecked should remove the highlight areas
    alert("Not highlighted");
}
});

    <label for="">Click to see differences</label>
<input type="checkbox" class="check-diff">
<div class="compare-diff">
    <div class="row header">
        <div class="col-sm-3 title">Name</div>
        <div class="col-sm-3">John</div>
        <div class="col-sm-3">Henry</div>
        <div class="col-sm-3">Kim</div>
    </div>
    <div class="row">
        <div class="col-sm-3 title">Status</div>
        <div class="col-sm-3 diff">Single</div>
        <div class="col-sm-3 diff">Married</div>
        <div class="col-sm-3 diff">Single</div>
    </div>
    <div class="row">
            <div class="col-sm-3 title">Car</div>
            <div class="col-sm-3 diff">Yes</div>
            <div class="col-sm-3 diff">Yes</div>
            <div class="col-sm-3 diff">Yes</div>
    </div>
</div>

2 个答案:

答案 0 :(得分:1)

以下jquery代码怎么样?

$('.check-diff').click(function() {
if($(this).prop('checked')){
    checkDiff();
} else{
    $(".row").each(function(){
        $(this).css("background-color","#fff");
    });
}
});

function checkDiff(){
$(".row").each(function(){
    var diff = false;
    var source = $(this).find(".diff").first().text();
    $(this).find(".diff").each(function(){
        var compare = $(this).text();
        if(source != compare){
           diff = true;
        }
    });   
    if(diff == true){
        $(this).css("background-color","red");
    }
 });
}

希望我帮到你,你会有一个想法,如何继续前进! :)

答案 1 :(得分:1)

您可以为要检查的行使用2个每个循环和一个类名。只会验证具有类名row的{​​{1}}和具有类名checkDiff的单元格。

JSnippet DEMO - validate difference in rows base on the cell text

JS:

diff

HTML:

$(function(){

    $('.check-diff').click(function() {
        if($(this).prop('checked')){
            $('.row.checkDiff').each(function(i,ele){
                var values = $(ele).find('.diff');
                var first = values.eq(0).text();
                var diff = false;
                values.each(function(j,e){
                    if ($(e).text() !== first) diff = true;
                });
                if (diff) $(ele).addClass('highlight');
            });
        } else{
            $('.row.checkDiff').removeClass('highlight');
        }
    });

});