2012-01-02 94 views
2

我正在用一行代码来完成此操作。将div ID转换为字符串

var a = ''; 
    $('#MyDivs div').each(function(){a+=this.id+',';}); 
    a = a.substring(0,a.length-1);// remove the last comma 

我虽然这样做会做到这一点,但无济于事。我在正确的轨道上?

$('#MyDivs div[id]').join(', '); 
+0

尝试$(本).attr( “ID”),而不是this.id – 2012-01-02 07:16:48

+2

@RajatSinghal' $(this).attr('id')'与'this.id'相同,只不过第一个是jQuery方式。 – Nathan 2012-01-02 07:18:23

+1

可能重复[如何使用jQuery获取所有ID?](http://stackoverflow.com/questions/827294/how-to-get-all-of-the-ids-with-jquery) – 2012-01-02 08:41:56

回答

7

在这里,你在一行去:

var a = $('#MyDivs div[id]').map(function(){ return this.id }).get().join(', '); 

这里的小提琴:http://jsfiddle.net/tGFeZ/

+0

不错, get()转换为数组。每天学习新的东西:) – Marlin 2012-01-02 07:31:24

+0

甜,我知道它可以完成。干杯。 – 2012-01-02 08:01:06

2

这应该提供一些帮助:How to get all of the IDs with jQuery?

有一个行示例在那里,虽然它可能不是最有吸引力的解决方案。

+0

谢谢。在发布之前,我至少搜索了10分钟的答案。猜猜我需要处理我的搜索条件:/ – 2012-01-02 08:02:05

2

如果用“单行”表示单个语句,则此库不可行。如果你只是在寻找一串简短的陈述,那么下面就会做到。但是,即使下面应该在多行中表示可读性

$.makeArray($('#MyDivs div[id]').map(function(){return this.id})).join(','); 

下同:

$.makeArray($('#MyDivs div[id]').map(function(){ 
    return this.id 
}).join(',');