javascript/jQuery - For Loop

use*_*855 17 javascript jquery loops for-loop

我有一个查询ajax响应,然后我用它来设置数组变量.无论如何使用'For Loop'更改为#name,这样我就不必编写一行代码来设置每个数组元素.

array[0]=$('#event00',response).html();
array[1]=$('#event01',response).html();
array[2]=$('#event02',response).html();
array[3]=$('#event03',response).html();
Run Code Online (Sandbox Code Playgroud)

因此,'#event00'可以在for循环中用于更改为'#event01'等

Gre*_*reg 40

使用常规for循环并格式化要在选择器中使用的索引.

var array = [];
for (var i = 0; i < 4; i++) {
    var selector = '' + i;
    if (selector.length == 1)
        selector = '0' + selector;
    selector = '#event' + selector;
    array.push($(selector, response).html());
}
Run Code Online (Sandbox Code Playgroud)


小智 8

这样的事情怎么样?

var arr = [];

$('[id^=event]', response).each(function(){
    arr.push($(this).html());
});
Run Code Online (Sandbox Code Playgroud)

[attr^=selector]选择匹配上的元素attr属性与给定的字符串,你不关心"事件"后的数字,这样开始.


Bot*_*Bot 2

.each()应该为你工作。http://api.jquery.com/jQuery.each/http://api.jquery.com/each/或者您可以使用.map.

var newArray = $(array).map(function(i) {
    return $('#event' + i, response).html();
});
Run Code Online (Sandbox Code Playgroud)

编辑:我删除了添加前缀 0,因为建议不要使用它。

如果你必须使用它

var newArray = $(array).map(function(i) {
    var number = '' + i;
    if (number.length == 1) {
        number = '0' + number;
    }   
    return $('#event' + number, response).html();
});
Run Code Online (Sandbox Code Playgroud)