2013-04-27 60 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()); 
    }); 
});