1

早上好,我有这段代码应该将数字分类为奇数和偶数类别。它通过检查数字并在必要时创建一个新类别来做到这一点。在创建新类别后,它会立即附加一个包含数字的新行。问题是它倾向于跳过新类别的第一个元素(即1和2不包括在相应的类别中)。

我可以通过再次搜索类别来解决这个问题(注释掉代码(jsfiddle l:12)),但是我想从 addNewCategory 函数中获取新创建的类别元素,这可能吗?

var content = $('#content');

// add one row to the category
var addRow = function (number) {
    var categoryId = (number % 2 == 0 ? 'even' : 'odd'),
        $category = content.find('#category_' + categoryId)
    ;

    // category exists?
    if(!$category.length) {
        $category = addNewCategory (number);
        //$category = content.find('#category_' + categoryId);
    }

    // prepare new row
    var row = '<div class="row">' + number + '</div>';
    $category.append(row);
};

    // add new category
var addNewCategory = function(number) {
    var categoryId = (number % 2 == 0 ? 'even' : 'odd'),
        category = '<div class="category" id="category_' + categoryId + '">' + categoryId + '</div>';

    content.append(category);
    return $(category);
};

// start
for(var i = 1; i < 10; i++) {
    addRow(i);
}

jsfiddle:jsfiddle

4

2 回答 2

2

试试.appendTo()

var addNewCategory = function(number) {
    var categoryId = (number % 2 == 0 ? 'even' : 'odd'),
        category = '<div class="category" id="category_' + categoryId + '">' + categoryId + '</div>';

    return $(category).appendTo(content)
};
于 2013-07-16T07:30:38.493 回答
0

我已将您的 Fiddle 更新为该代码http://jsfiddle.net/rdhTa/1/

var content = $('#content');

// add one row to the category
var addRow = function (number) {
    var categoryId = (number % 2 == 0 ? 'even' : 'odd');
    var category = content.find('#category_' + categoryId) ;

    // category exists?
    if(category.length == 0) {
        addNewCategory (number);
        category = content.find('#category_' + categoryId);
    }

    // prepare new row
    var row = '<div class="row">' + number + '</div>';
    category.append(row);
};

    // add new category
    var addNewCategory = function(number) {
    var categoryId = (number % 2 == 0 ? 'even' : 'odd'),
    category = '<div class="category" id="category_' + categoryId + '">' + categoryId + '</div>';

    content.append(category);
    return;
};

// start
for(var i = 1; i < 10; i++) {
    addRow(i);
}
于 2013-07-16T07:33:51.177 回答