2016-11-23 4 views
0

私は2ブロックのコードを1ブロックにする方法を模索しています。これどうやってするの?私は試してみましたが、一度に1つのコンテナのみから子供をどのようにターゲットにするかはわかりません。jQueryのこのようなラジオボタンのような機能を単純化して修正するには?

どうすればこの問題を解決できますか?

values = (function() { 
 

 
    var valueOne = '.block-v1'; 
 
    $(valueOne).each(function(index) { 
 
    $(this).click(function() { 
 
     if ($(this).hasClass('active')) { 
 
     } else { 
 
     $(valueOne).removeClass('active') 
 
     $(this).addClass('active'); 
 
     } 
 

 
     var number1 = $(this).attr("data-nub"); 
 
     test(number1) 
 

 
    }); 
 
    }); 
 

 
    var sub = '.block-v2'; 
 
    $(sub).each(function(index) { 
 
    $(this).click(function() { 
 
     if ($(this).hasClass('active')) { 
 
     } else { 
 
     $(sub).removeClass('active') 
 
     $(this).addClass('active'); 
 
     } 
 

 
     var number2 = $(this).attr("data-nub"); 
 
     test(number2) 
 
    }); 
 
    }); 
 

 

 
    test = (function (number1, number2) { 
 
    $('.nub-result-target').html(number1 + number2); 
 
    }); 
 

 
})(this, jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> 
 
<div class="blocks"> 
 
    <div id="one" data-nub="1" class="block block-v1 active">block-v1 1</div> 
 
    <div id="two" data-nub="2" class="block block-v1">block-v1 2</div> 
 
</div> 
 

 
<div class="blocks sub"> 
 
    <div id="sub-one" data-nub="3" class="block block-v2">block-v2 1</div> 
 
    <div id="sub-two" data-nub="4" class="block block-v2 active">block-v2 2</div> 
 
</div> 
 

 
<div class="blocks nub-result"> 
 
    <div class="nub-result-values">numbers: <span class="nub-result-target">temp</span> 
 
    </div> 
 
</div>

答えて

1

values = (function() { 
 
    var number1 = $('.block-v1.active').attr('data-nub'), 
 
     number2 = $('.block-v2.active').attr('data-nub'); 
 

 
    $('.block').each(function(index) { 
 
    $(this).click(function() { 
 
     var val = $(this).attr('data-nub'); 
 

 
     $(this).addClass('active') 
 
      .siblings().removeClass('active'); 
 

 
     if ($(this).hasClass('block-v1')) { 
 
     number1 = val; 
 
     } else { 
 
     number2 = val; 
 
     } 
 

 
     $('.nub-result-target').html(number1 + number2); 
 
    }); 
 
    }); 
 
})(this, jQuery);
.active { 
 
    background: gold; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> 
 
<div class="blocks"> 
 
    <div id="one" data-nub="1" class="block block-v1 active">block-v1 1</div> 
 
    <div id="two" data-nub="2" class="block block-v1">block-v1 2</div> 
 
</div> 
 

 
<div class="blocks sub"> 
 
    <div id="sub-one" data-nub="3" class="block block-v2">block-v2 1</div> 
 
    <div id="sub-two" data-nub="4" class="block block-v2 active">block-v2 2</div> 
 
</div> 
 

 
<div class="blocks nub-result"> 
 
    <div class="nub-result-values">numbers: <span class="nub-result-target">temp</span> 
 
    </div> 
 
</div>

関連する問題