我正在寻找一种方法,只需一个块就可以生成两个代码块。我怎样才能做到这一点?我一直在努力,但我不知道如何一次只从一个容器中瞄准孩子。
我该如何解决这个问题?
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>
答案 0 :(得分: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);
&#13;
.active {
background: gold;
}
&#13;
<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>
&#13;