2013-07-16 241 views
1

早上好,我有這個代碼應該將數字分類成奇數和偶數類別。它通過檢查數字並在必要時創建新類別來實現。在創建新類別後,會附加一個包含數字的新行。問題是它傾向於跳過新類別的第一個元素(即1和2不包含在相應的類別中)。jQuery返回附加元素

我可以通過再次搜索一個類別(註釋掉代碼(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

+0

也許變種I = 0? – Virus721

回答

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) 
}; 
+0

這正是我所需要的,謝謝。但爲什麼它不能與'append'一起使用? – DeadMoroz

0

我有你的小提琴更新爲代碼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); 
}