2013-04-27 57 views
1

我試圖讓元素在頁面上的輸出,這一點:獲取所有的ID開始以「X」

$('a#exportPage').on('click',function(){ 
ExportIds = $('[id^="appendHeading"]').attr('id'); 
ExportTexts = $('[id^="appendHeading"]').text(); 
$("#PrintIds").append("ObjectID:"+ExportIds+"Content:"+ExportTexts); 
}); 

,但只得到「最後的ID」,但不是所有的人。我以前遇到過這個麻煩,需要把它放在我的腦海中!

我想要的輸出是 「對象ID:appendHeading,內容:文本,對象ID:appendHeading,內容:文本」 等,

提前感謝!

回答

0

你應該總是緩存在一個變量,慢的選擇jQuery的對象,如果你打算使用它們不止一次。所以我將它緩存在一個名爲$els的變量中。然後我做了一個調整,因爲attr只返回第一個匹配元素的屬性,並且text返回一個字符串而不是一個字符串數組。我用map創建包含所需值的jQuery對象,然後我用get來轉換jQuery對象到一個數組:

$('a#exportPage').on('click',function(){ 
    var $els = $('[id^="appendHeading"]'); 
    ExportIds = $els.map(function(){ 
     return this.id; 
    }).get(); 
    ExportTexts = $els.map(function(){ 
     return $(this).text(); 
    }).get(); 
    $("#PrintIds").append("ObjectID:"+ExportIds+"Content:"+ExportTexts); 
}); 

如果你想輸出的每個ID,文本對而不是全部IDS之後的所有文字,你可能想進一步改寫這樣的:

$('a#exportPage').on('click',function(){ 
    var textMap = {}; 
    $('[id^="appendHeading"]').each(function(){ 
     textMap[this.id] = $(this).text(); 
    }); 
    for(id in textMap) 
     $("#PrintIds").append("ObjectID:" + id + "Content:" + textMap[id]); 
}); 

甚至:

$('a#exportPage').on('click',function(){ 
    $('[id^="appendHeading"]').each(function(){ 
     $("#PrintIds").append("ObjectID:" + this.id + "Content:" + $(this).text()); 
    }); 
}); 
+0

非常感謝你的一個很好的解釋!而你花了你的時間!萬分感激! – Kim 2013-04-27 23:35:38

1

可能是你需要的東西是這樣的:

$('a#exportPage').on('click', function() { 
    $('[id^="appendHeading"]').each(function() { 
    $("#PrintIds").append('ObjectID: ' + $(this).attr('id') + 'Content: ' + $(this).text()); 
    }); 
}); 
0

使用每個()。

$('a#exportPage').on('click',function(){ 
    var PrintIds = $('#PrintIds'); 
    $('[id^="appendHeading"]').each(function() { 
    PrintIds.append('ObjectID:'+$(this).attr('id')+'Content:'+$(this).text()); 
    }); 
});