在jQuery中,检索了许多元素后,我用.each循环遍历它们,之后我将它们吐出画布。但是,我需要控制组中的元素,因此在100个元素中,10个将获得特定值,另外10个将获得不同的值集,依此类推。
据我所知,我无法在.each-loop中保持这种级别的控制。对于检索到的第一批x元素,没有任何函数可以执行此操作;其余的,做点别的。
我应该如何控制元素?
一些代码示例:
function handleData(item) {
var items = jQuery.parseJSON(item);
var id = items[0].id;
var something = items[0].something;
$.each(items, function(key, value) {
variableHolder[$counter-1] = value.id;
variableHolder["intellect"] = value.intellect;
my_obj[$counter] = example.library.text({
value: "something",
example: "one"
});
这是我需要控制的$ counter变量。我想分批运行它。计数器中的前20个元素获得一种类型的值,依此类推。
答案 0 :(得分:1)
您可以使用slice()
方法(Ref。http://api.jquery.com/slice/)方法获取要循环的元素子集,以执行您想要的任何操作。这可以在每个典型的外部或之前完成。
答案 1 :(得分:0)
您可以使用这样的分块功能(代码段中的说明)
let chunk = ( arr, chunk = 1 ) => arr.reduce( ( acc, value, index, oArr, i = index + 1, s = oArr.slice.bind( oArr ), len = oArr.length ) => {
( i % chunk === 0 ) ? acc.push( s( i - chunk, i ) ): ( i === len ) && acc.push( s( i - ( i % chunk ), len ) );
return acc;
}, [] );
chunk(array, chunk_size);
//chunking function
//get the array and size of chunks
//reduce the array.
//the reducer function chunks if index+1 modulus the size of the chunk is zero
//if it is it pushes the chunk of the array using slice.
//if it is not it evaluates if it is the end of the array using a short-circuit AND( && )
//if it is the end of the array we push what we have left as its own chunk
//always returns the accumulated array.
let chunk = ( arr, chunk = 1 ) => arr.reduce( ( acc, value, index, oArr, i = index + 1, s = oArr.slice.bind( oArr ), len = oArr.length ) => {
( i % chunk === 0 ) ? acc.push( s( i - chunk, i ) ): ( i === len ) && acc.push( s( i - ( i % chunk ), len ) );
return acc;
}, [] );
//grab all the elements and turn them into an array
let elements = Array.from( $(".random") );
//chunk the elements into arrays of 10, the remainder will be dumped into the last array.
//log out each array.
chunk(elements, 10).forEach((arr) => console.log(arr));

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="random">1</div>
<div class="random">12</div>
<div class="random">3</div>
<div class="random">45</div>
<div class="random">6</div>
<div class="random">77</div>
<div class="random">88</div>
<div class="random">99</div>
<div class="random">1</div>
<div class="random">12</div>
<div class="random">3</div>
<div class="random">45</div>
<div class="random">6</div>
<div class="random">77</div>
<div class="random">88</div>
<div class="random">99</div>
<div class="random">000</div>
<div class="random">1</div>
<div class="random">12</div>
<div class="random">3</div>
<div class="random">45</div>
<div class="random">6</div>
<div class="random">77</div>
<div class="random">88</div>
<div class="random">99</div>
<div class="random">000</div>
&#13;