2015-06-04 40 views
0

我是jQuery的新手,希望有人能夠幫助我解決這個問題,並提供一個簡短的解釋,以便將來可以應用於類似的案例。jQuery:如何爲每個項目創建包含兩個值的數組

我有一個動態構建的大型HTML頁面。 該頁面包含幾個表,其中某些div可編輯(contenteditable = true)。這些div都具有類"editable"

現在我想爲所有這些divs創建一個包含它們的id和它們的內容(文本)的數組。

到目前爲止,我有以下應該創建這些div的唯一id與增加的數字,但我不知道如何爲此創建數組。 此外,出於好奇,是否有某個術語如何調用每個項目有兩個值的數組?

我的jQuery:

$('#btnSave').on('click', function(){ 
    var i = 0; 
    $(this).closest('form').find('div.editable').each(function(){ 
     $(this).attr('id', 'ed' + i+1); 
     if(($(this).text != '') && ($(this).text != ' ')){ 
      $(this).addClass('edited'); 
     } 
     i++; 
    }); 
}); 

// my attempt for the array (perhaps the wrong approach): 
var arrEdited = new Array(); 
$('div.edited').each(function(){ 
    arrEdited.push($.trim($(this).text())); 
}); 

提前許多感謝, 麥克

+1

不是'$(this).text',應該是'$(this).text()' –

回答

2

我不認爲你需要另一個循環,而不是你可以把你的第一個循環內,裏面if(($(this).text() != '') && ($(this).text() != ' ')),然後推了object你的陣列,而不是一個值。

var arrEdited = new Array(); 
$('#btnSave').on('click', function(){ 
    $(this).closest('form').find('div.editable').each(function(index){ 
     //you could use the index when you use .each function 
     $(this).attr('id', 'ed' + (index+1)); 
     if(($(this).text() != '') && ($(this).text() != ' ')){ 
      $(this).addClass('edited'); 
      //instead of using another loop, you can put your code here 
      arrEdited.push({ 
       id: $(this).attr('id'), 
       text: $.trim($(this).text()) 
      }); 
      //here you use an object, people call it array of objects 
     } 
    }); 
}); 
+0

感謝您的支持!你說得對,我的情況更好 - 感謝解釋。我會盡快接受。 :) – keewee279

+0

只需添加:在「attr」前面有一個缺失的點 - 我在我的文章中更正了這一點。 – keewee279

+1

@ keewee279,最好是使用'index'而不是'i',http://api.jquery.com/jquery.each/#jQuery-each-array-callback – Satpal

3

您應該使用array of objects存儲DIV idtext內部數組。

檢查:

// my attempt for the array (perhaps the wrong approach): 
var arrEdited = []; // [] is better than new Array() 

$('div.edited').each(function() { 
    // Add this div id and content in array 
    arrEdited.push({ 
     id: $(this).attr('id'), 
     text: $.trim($(this).text()) 
    }); 
}); 
+1

感謝您的支持。你能解釋爲什麼[]比新陣列更好嗎? – keewee279

3

您可以使用.map()創建一個數組。

通過函數傳遞當前匹配集合中的每個元素,產生一個包含返回值的新jQuery對象。

由於返回值是一個jQuery對象,它包含一個數組,因此在結果上調用.get()以處理基本數組非常常見。

var arrEdited = $('div.edited').map(function(){ 
    return { 
     id: this.id, 
     text: $.trim($(this).text()) 
    } 
}).get(); 
相關問題