如何将countup编号插入两个特定的HTML类

时间:2015-06-16 09:10:05

标签: jquery each

我正在迭代.each class="q-submit"并做一个简单的计数++。每个计数的结果都写入:class="number"

<div class="section">
    <div class="q-submit">
        <div class="number"></div>
    </div>
</div>
<div class="section">
    <div class="q-result">
        <div class="number"></div>
    </div>
</div>
<div class="section">
    <div class="q-submit">
        <div class="number"></div>
    </div>
</div>
<div class="section">
    <div class="q-result">
        <div class="number"></div>
    </div>
</div>

Jquery的:

submitContainer.each(function(){
    currentCount++;

    $(this).text(currentCount)
});

我的问题:我如何将计数编号插入class="q-result"数字类?

小提琴:http://jsfiddle.net/xLeh8y9u/

然后输出上面的内容:

q-submit - 1

q-result - 1

q-submit - 2

q-result - 2

4 个答案:

答案 0 :(得分:0)

试试这个:

var submitContainer = $('.q-submit');
var currentCount = 0;

submitContainer.each(function(){
    currentCount++;   
     $(this).find('.number').text(currentCount).end().closest('.section').next().find('.number').text(currentCount);
});

<强> DEMO

答案 1 :(得分:0)

在代码中查看内联注释:

var counter = {
    'q-submit': 0, // Initialize the counter to zero
    'q-result': 0
}; // Counter for both the classes

var className = ''; // For getting classname of the current element in loop


// Iterate over .section
$('.section').each(function () {
    className = $(this).children('div').attr('class');
    // Get the class name of the direct child of current .section

    counter[className] += 1;
    // Increment the counter of the current class by one

    $(this).find('.number').text(className + ' => ' + counter[$(this).children('div').attr('class')]);
    // Add text of class and counter in the .number inside current .section
});

演示:http://jsfiddle.net/tusharj/xLeh8y9u/5/

答案 2 :(得分:0)

您可以遍历元素,获取第一个元素并设置值 here是使用中显示它的小提琴

var submitContainer = $('.q-submit');
var currentCount = 0;

submitContainer.each(function(){
    currentCount++;
    setCurrentCount();
    $(this).text(currentCount);
});

function setCurrentCount(){
    $(".q-result .number").each(function(result){
        if($(this).text()===""){            
            $(this).text(currentCount);
            return false;
        }        
    });
}

答案 3 :(得分:0)

对于每个类,对于该类的每个成员,在集合+ 1中输出其位置:

$.each(['.q-submit', '.q-result'], function(_, cl) {
  $(cl).each(function(idx) {
    $(this).text(idx+1);
  });
});

Fiddle